Pregunta

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();
¿Fue útil?

Solución

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).

Otros consejos

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..

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top