问题描述
我在这个程序中创建了两个文件:“OutputFile.txt”和“InputFile.txt”。当我运行我的代码时,它显示一个名为“java.io.FileNotFoundException”的错误,但它在我的系统中创建了“OutputFile.txt”而不是“InputFile.txt” 这是为什么?
public static void main(String[] args) throws IOException{
// 2 File objects are created: outFile and inFile,this will create text files in my system
File outFile = new File("OutputFile.txt");
File inFile = new File("InputFile.txt");
// These FileWriter Objects are created to allow the File Object to be writable to readable
FileWriter out = new FileWriter(outFile);
FileReader in = new FileReader(inFile);
// these closes files after use in program
out.close();
in.close();
}
解决方法
创建了 2 个文件对象:outFile 和 inFile,这将在我的系统中创建文本文件
第一部分是正确的;第二个不是。创建 File
对象不是创建文件; new File(...)
只是制作一个存储路径的对象,基本上,不会以任何方式接触磁盘。每个文档,File
对象是
文件和目录路径名的抽象表示。
FileWriter
和 FileReader
确实接触磁盘。 FileWriter
写入文件,如果文件不存在则创建一个; FileReader
不写,它读——如果文件不存在,它会抱怨。