I created two files in this program: “OutputFile.txt” and “InputFile.txt”. When I run my code, it displays an error called “java.io.FileNotFoundException” but it created “OutputFile.txt” in my system but not “InputFile.txt” Why is that?
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(); }
Advertisement
Answer
2 File objects are created: outFile and inFile, this will create text files in my system
The first part of this is correct; the second is not. Creation of a File
object is not creation of a file; new File(...)
just makes an object that stores a path, basically, and does not touch the disk in any way. Per docs, a File
object is
An abstract representation of file and directory pathnames.
FileWriter
and FileReader
do touch the disk. FileWriter
writes to a file, and will create one if it does not exist; FileReader
does not write, it reads — and if the file does not exist, it complains.