Java: 为什么我的程序在成功创建输出文件时收到创建输入文件的 java.io.FileNotFoundException 错误?
Java: Why does my program receive java.io.FileNotFoundException error for creating an input file when it successfully creates an output file?
我在这个程序中创建了两个文件:“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 File objects are created: outFile and inFile, this will create text files in my system
第一部分是正确的;第二个不是。创建 File
对象不是创建文件; new File(...)
只是制作一个存储路径的对象,基本上不以任何方式接触磁盘。根据文档,File
对象是
An abstract representation of file and directory pathnames.
FileWriter
和 FileReader
确实接触了磁盘。 FileWriter
写入文件,不存在则创建; FileReader
不写入,它读取 — 如果文件不存在,它会抱怨。
我在这个程序中创建了两个文件:“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 File objects are created: outFile and inFile, this will create text files in my system
第一部分是正确的;第二个不是。创建 File
对象不是创建文件; new File(...)
只是制作一个存储路径的对象,基本上不以任何方式接触磁盘。根据文档,File
对象是
An abstract representation of file and directory pathnames.
FileWriter
和 FileReader
确实接触了磁盘。 FileWriter
写入文件,不存在则创建; FileReader
不写入,它读取 — 如果文件不存在,它会抱怨。