Reputation: 97
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();
Upvotes: 0
Views: 138
Reputation: 298
bufferedReader.close() must use in the end of where you close this operation..
Upvotes: 0
Reputation: 823
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
Upvotes: 0
Reputation: 326
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).
Upvotes: 2