문제

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top