I saved the text1.txt file in the same folder as the Algo.java file is in. But i get a Filenotfoundexception and i can't find any reason for that

StackOverflow https://stackoverflow.com/questions/23516285

Question

I saved the text1.txt file in the same folder as the Algo.java file is in. But i get a Filenotfoundexception and i can't find any reason for that.

import java.io.*;
import java.util.logging.Level;
java.util.logging.Logger;

public class Algo{

 static void naive(){
  BufferedReader file1;
 try{
   file1=new BufferedReader(new FileReader("text1.txt"));
  String T=file1.readLine();
  System.out.println(T);
 }
  catch (FileNotFoundException ex) {
        Logger.getLogger(Algoq1.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Algoq1.class.getName()).log(Level.SEVERE, null, ex);
    }
 }

    public static void main(String args[]){
      Algo.naive();
    }
  }
Was it helpful?

Solution 2

"I saved the text1.txt file in the same folder as the Algo.java file is in. But i get a Filenotfoundexception and i can't find any reason for that"

Then read the file from the class path. You can get an InputStream from Algo.class.getResourceAsStream()

InputStream is = Algo.class.getResourceAsStream("text1.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));

When you try to read it as a File, which is the case when use FileReader(String path), file will be search within the file system, and in your IDE the search will begin from the working directory that is specified (normally the project root). So for the FileReader to work, with just the name of the file passed, the file should be in the working directory.

Depending on the requirements, whether the application is specific to your system or should be distributed on other systems, you need to make the decision whether the file should be read from the class path, or the file system.

OTHER TIPS

Put resources separately form your code to make it manageable and reusable for other different package's classes also.

Try with other options.

// Read from same package 
InputStream in = Algoq1.class.getResourceAsStream("text1.txt");

// Read from resources folder parallel to src in your project
File file = new File("resources/text1.txt");

// Read from src/resources folder
InputStream in = Algoq1.class.getResourceAsStream("/resources/text1.txt");

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top