I created a method that takes a File. Here is my code.
I have a tester on another file that create a File and calls ClassName.turnOffMasterDebugger(f). The problem I am running into is it does not read anything?
I tried to investigate and the code run but it does not go into the while loop. I check if the file and there is a file created with some text inside.
BufferedReader reader = new BufferedReader(new FileReader(f)); this line does not seem to work.
First of all, "doesn't work" is the bane of a help website like this. Does it pass that line and not do anything? Does it throw an exception? Does your computer halt and catch fire? What?
Assuming that other implied things are true, it is most likely your file name that is incorrect. Is it a filename without a path? relative pathname? absolute pathname? link pathname?
Try separating the steps and put in some trace statements or debug breakpoints. Create the file reader in one statement, and the buffered reader in another. What is the value of the filename before you create the filereader? If it is not an absolute pathname, then is it relative to the right place?
More than half of debugging a problem like this is a conviction that there IS an error in your code or data somewhere. There isn't much here, so you shouldn't have far to look.
The way you have your while loop set up, the first line of the file is going to get discarded. Does your test file only have one line in it? Aside from that, though, your code looks fine--so if there is a problem, it's happening "off stage", so to speak. You haven't included the catch block in your code snippet. Are you printing the error message from any exceptions that get thrown?
Here is what I had done.
I created a file, wrote to the bufferWriter (stream), and then passed the file to my method.
What I had done wrong is I did not close the writer before I pass it.
It works now and no my computer did not catch a fire.
I do have the catch block on my code and there is no exceptions. I did not include that above since my original question is if there is a special case for passing a File.
Kurt Van Etten
Joined: Sep 07, 2010
That's an interesting quirk in how file i/o works. I would have thought that the FileReader constructor would throw an exception if the file was already open for output elsewhere, but it doesn't--that's something good to be aware of. (I guess that makes sense, on second thought, since that's something that's being handled at the O/S level and not in the JVM.)
Oh, here is something else interesting that I just tried: calling flush() on the output stream also fixes the problem. So I guess the problem isn't so much that the file was still open, but that the data hadn't been written out to it yet!