使用
FileInputStream
和处理文件FileOutputStream
。 我正在读 Schildt 的书,并开始处理文件。该示例表示您需要从命令行运行该程序并输入文件名。但我正在 IntelliJ 学习。如何通过指定文件路径来处理文件?这是一个例子:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFile {
public static void main(String[] args) {
int i;
FileInputStream fin;
FileOutputStream fout;
if (args.length != 2) {
System.out.println("Usage: CopyFile From To.");
return;
}
try {
fin = new FileInputStream(args[0]);
} catch (FileNotFoundException exc) {
System.out.println("Input file not found.");
return;
}
try {
fout = new FileOutputStream(args[1]);
} catch (FileNotFoundException exc) {
System.out.println("Error opening output file.");
try {
fin.close();
} catch (IOException exc2) {
System.out.println("Error closing input file.");
}
return;
}
try {
do {
i = fin.read();
if (i != -1) fout.write(i);
} while (i != -1);
} catch (IOException exc) {
System.out.println("Fi;e error.");
}
try {
fin.close();
} catch (IOException exc) {
System.out.println("Error closing input file.");
}
try {
fout.close();
} catch (IOException exc) {
System.out.println("Error closing output file.");
}
}
}
GO TO FULL VERSION