0

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();
blackpanther
  • 10,998
  • 11
  • 48
  • 78
digrev
  • 97
  • 1
  • 6
  • 2
    `dataInputStream` is out of scope, so your code cannot reference it. Post the stack trace for more help. The file is probably missing. – Deepak Bala Apr 11 '13 at 18:45
  • Declare DataInputStream outside the try block and then you will be able to close it at the bottom. – Nico Apr 11 '13 at 18:48
  • It's likely that the file is embedded within the application jar, you may need to use getClass().getResource("myfile.txt") instead – MadProgrammer Apr 11 '13 at 18:50
  • @MadProgrammer He mentions he manually placed the file in the project folder. – Guillermo René Ramírez Apr 11 '13 at 18:53
  • @GuillermoRenéRamírez precisely, define "project folder", if its become part of the Jar (or internal resource from the perspective of the JVM), then the OP will need to use the Classloader to reference it. If its within the same directory as the project is executed, then the above code should work – MadProgrammer Apr 11 '13 at 18:55
  • Please don't use DataInputStream to read a text file. You don't need it so please remove it as people might copy this code. – Peter Lawrey Apr 24 '13 at 07:46

3 Answers3

2

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

0

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

Sajith Silva
  • 823
  • 1
  • 13
  • 24
  • If the file is within the same package (or class path) the OP should be using getClass().getResource(...) which will use the class path as a context for performing its search (relative to it) – MadProgrammer Apr 11 '13 at 19:05
0

bufferedReader.close() must use in the end of where you close this operation..

Manoj Gupta
  • 298
  • 1
  • 4
  • 20