"2. Create a Reader or a Writer or a Stream. Specifically, create a FileReader, a FileWriter, a PrintWriter, a FileInputStream, or a FileOutputStream. Whenever you create an instance of one of these classes, you automatically create a file, unless one already exists,"
I tried to do this:
File f2 = new File("File3");
System.out.println("does the file2 exist?: " + f2.exists());
FileReader fr2 = new FileReader(f2);
When I run it:
does the file2 exist?: false Exception in thread "main" java.io.FileNotFoundException: File3 (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Unknown Source) at java.io.FileReader.<init>(Unknown Source) at chapter7.files.FileTest2.main(FileTest2.java:54)
Can someone pls explain me why the file didn't create when I created the FileReader instance?.. thanks.
I tried the code that you have posted. Even I am getting the same exception. But when you replace FileReader with FileWriter, it works.
Also if you will see the API on page 436 for FileReader...you'll notice that there is only read() method......so I think there is no sense in creating a new File(when file is not present) and reading it...since new file would be BLANK....so read() would return NULL..... [ May 13, 2008: Message edited by: Vinayak Jallapelli ]
File objects can be created for anything and everything, whether it exists or not (A File object can be used for creating a file, though, and for checking whether a file exists, so it makes sense to create them for non-existing files.)
You can't read from non-existing files, so the exception shouldn't surprise. Note that non-existing files are not the same as zero-sized files, so FileReader shouldn't go ahead and create a file if it doesn't exist.
On the other hand, it is perfectly possible to write to non-existing files; that's why you're not getting an exception there. [ May 13, 2008: Message edited by: Ulf Dittmer ]
File f = new File("file1.txt") does not create the file on the disk, it just checks whether the file is there and will not create if the file if it is not there, thta is why when we check f.exists(), it gives false.. To create the file on disk if file doesn't exits use f.createNewFile() and now check f.exists();
I think you must first write th file and read
File f = new File("file1.txt") FileWriter fw = new FileWriter() // this wil create the new file and and also FileWriter object
FileReader fr = new FileReader(f) String s = f.read() // this will read the whole file
Please correct me if i am wrong. [ May 13, 2008: Message edited by: Dinesh Tahiliani ]