i was doing a sample about reading files. I put a txt file into project folder and wrote this code but I got the exception FileNotFound and also when I try to close dataInputStream I am getting compile error(commented out line). I think I messed up everything
String str=null;
try {
FileInputStream fileInputStream=new FileInputStream("myfile.txt");
DataInputStream dataInputStream=new DataInputStream(fileInputStream);
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(dataInputStream));
str=bufferedReader.readLine();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(str);
//dataInputStream.close();
Java is really nitpicky about relative paths, so `"myfile.txt" should probably live wherever your project is being built.
As for closing the dataInputStream, it is not in scope. Declare it outside of your try block. In any case, I'd suggest placing the actual close() call in a finally block to make sure it is always done (if the reference isn't null).
I agree with Guillermo
myfile.txt needs to be in your class path.
If you run this code in command line, it should be located in the same folder as this code executes, or same package.
as for the datainput stream it is out of scope
bufferedReader.close() must use in the end of where you close this operation..
Related
I'm trying to write to a file using FileOutputStream. When the user selects what file to write to, the program tries to create a FileOutputStream using that file, to check if it works. If it does not, the user has to select a different file. If it does work, the FileOutputStream is closed.
After a file, for which a FOS can be opened, has been selected the program tries again to create another FOS, but this sometimes fails.
I know that you cannot write to a file when it is open on your computer. Could it be that the first FOS has not been "fully closed" and therefore the file is still considered open, so that the second FOS can not write to it?
In the following code, what happens is that the first creation and closing of the FOS does not throw an exception, while the second one somehow does. How can this be?
(I know the problem can be solved by simply using the first FOS and not creating a second, but I am interested in understanding why this particular code behaves the way it does.)
try {
FileOutputStream out1 = new FileOutputStream(file);
out1.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileOutputStream out2 = new FileOutputStream(file);
} catch (Exception e) {
e.printStackTrace();
}
Based on the symptoms, I surmise that you are using Windows, and the error you are getting in the second open is "file is in use".
Apparently under some circumstances, Windows does not immediately close a file when the application (in this case the JVM) closes the FileHandle:
FileStream.Close() is not closing the file handle instantly
Delay between CloseHandle function call and SMB Close request
This is not Java's doing, and I am not aware of a workaround (in Java) apart from waiting a bit and retrying.
(You could see what happens if you add a Thread.sleep(1000); before the 2nd attempt to create a FileOutputStream.)
in my eclipse when i run it, everything works fine and audio is okay, but i have problem when i create my .jar executable file. Audio file is in my package and i read it with getResourceAsStream so i just want to let you know. Here is problem..
InputStream input = getClass().getResourceAsStream("/optician/funny-doorbell.wav");
AudioInputStream audioIn;
try{
Clip clip;
audioIn = AudioSystem.getAudioInputStream(input);
clip=AudioSystem.getClip();
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException | IOException e1) {
e1.printStackTrace();
} catch (LineUnavailableException e1) {
e1.printStackTrace();
}
In this first case when i run with eclipse, it works fine, but when i run .jar executable file i get : reset/mark not supported.
Second case is everything same but :
BufferedInputStream input = (BufferedInputStream) getClass().getResourceAsStream("/optician/funny-doorbell.wav");
So everything is same, point is this that i now try with BufferedInputStream but the problem i get now is : Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: sun.new.www.protocol.jar.JarURLConnection$JarURLInputStream cannot be cast to java.io.BufferedInputStream
I tried in linux and windows but it doesn't works. Where is the problem ?
I think this question has been asked and answered before. See the accepted answer here for a detailed explanation: java.io.IOException: mark/reset not supported
That said, I believe you can fix your code by modifying your first line as follows:
InputStream input = new BufferedInputStream(getClass().getResourceAsStream("/optician/funny-doorbell.wav"));
The reason you're seeing a difference in behavior is that in Eclipse, getResourceAsStream is returning an InputStream that supports read/mark. When you run out of a jar, you're getting an implementation of InputStream that does not support read/mark (JarURLInputStream).
If you wrap the returned input stream in a new BufferedInputStream, you'll have read/mark support in the stream when you're running in a jar and your code will work everywhere.
Also, you're getting the ClassCastException because you're trying to cast the input stream returned by getResourceAsStream() to BufferedInputStream. Don't cast it; instead, wrap the returned input stream in a new BufferedInputStream() as I did in the code snippet above.
This question already has answers here:
Why does a Try/Catch block create new variable scope?
(5 answers)
Closed 8 years ago.
I have the following code, which works nicely in my class reading a file line by line.
try { FileInputStream in = new FileInputStream(filename);
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
String line;
while((line=reader.readLine())!=null){
// read the file
}
}
catch (Exception e) {
System.out.println(e);
}
But if I try to add the command close, for after the file was finished reading, then I got the error:
in.close();
Error:(131, 9) java: cannot find symbol
symbol: variable in
location: class ReadFile
I searched about cleaning objects after use and the need to close files before your program ends. And found several posts on this for Java, but many are very contradictory. The point is that in the end I just get very confused.
Am I wrong, or Java programming is a little bit fuzzy and messy? I mean, there is apparently no real use of destructor, the use of finalize is very questionable, and the use of close is also suggested as unnecessary. Some of the posts on these issues are contradictory and non-conclusive.
So, how to proceed here? In the case I really need to close the file, how to get rid of this error message? Is it really dispensable and unnecessary to close files? What about cleaning up class instances for the the program finishes?
You are getting the error because you have defined variable in inside the try block, so it is not visible in catch/finally/or anywhere outside that try. Move the declaration outside try:
Change this
try { FileInputStream in = new FileInputStream(filename);
to
FileInputStream in = null;
try { in = new FileInputStream(filename);
you may be closing in.close() out side try block so obviously you will get error because in is defined in try block which is local.
Better to use try with resource so you need not to manually close file stream
Ideally you must call the close() method inside the finally block, after the null check.
And for that you need to declare the variable in outside the try block.
Calling the close() method in finally block ensures that it is called irrespective of whether an Exception is thrown or not by the code in try block.
EDIT : This is when you are using Java 6 or earlier version. For Java 7 and higher you could use try with resource as suggested by #JqueryLearner
I use the following code to write some data to files:
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(...);
writer.flush();
}
finally {
if (writer != null)
writer.close();
}
After invoking the method multiple times I got a FileNotFoundException because too many files are open.
Obviously java does not close the file handles when I close the writer stream. Closing the FileWriter separately does not help.
Is there sth. I can do to force java to close the files?
Your code looks fine. It could be another part of your application which is leaking file handles.
You can monitor file handles using lsof on Linux or pfiles on Solaris. On Windows, you can use ProcessExplorer.
No, Java does close the file handles when you close the writer. Its actually built using Decorator pattern. Hence, it must be something else. Show the stack trace.
See this thread about writing to files, good tips there.. pay attention to the finally block in Anons reply.
BufferedWriter closes the underlying stream. Probably, this a multithreading issue. You can keep an instance of FileOutputStream and close it. Something like:
java.io.FileOutputStream out = new java.io.FileOutputStream(file);
try {
// make buffered writer, etc.
} finally {
out.close();
}
i noticed in a java program the below line used to open a file and process it
BufferedReader inp = new BufferedReader(new FileReader(inputFile));
In the javaprogram the inp is not closed before exiting the program the below line is missing
if (inp != null)
try {
inp.close();
} catch (IOException logOrIgnore) {}
The program has exits in a lot of place but they had not closed the file. Do i need to put this line everywhere? If i dont close the file when the program exits will it be a issue.
Does the garbage collector closes the file?
You should use try/finally:
Reader inp = new BufferedReader(new FileReader(inputFile));
try {
// Do stuff with "inp"
} finally {
IOUtils.closeQuietly(inp);
}
IOUtils is from Apache Commons IO. Its closeQuietly method is like your code snippet above: it calls close, and ignores any exceptions thrown.
The garbage collector does not close the file. If you know your program will not be long running or open many files, you can get away without closing the file. But otherwise you need to close it manually.
It sounds like you're using the BufferedReader without returning to the context in which it was declared (possibly an instance variable?). In that instance, you must close it manually upon each possible exit from your application. You cannot rely on the garbage collector to do this for you.