Question

I am having trouble reading from a file. Here is my code can anyone show me where I am wrong?

    public static Map<Route, List<Service>> read(String fileName)
        throws IOException, FormatException {


    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String strLine;
    while((strLine = reader.readLine())!= null)       
      {
        /* Own Code */          
      }
    reader.close();
}

I am having a FileNotFound Exception. May this be a the location of my file that is wrong?

Was it helpful?

Solution

You seem to want to use a resource. A resource is not accessed as a file, it is better to use it as a stream.

InputStream resourceStream = MyClass.class.getResourceAsStream(fileName);
BufferedReader myReader = new BufferedReader(new InputStreamReader(resourceStream));

Above code takes the location of your class in account, so you can simply use the fileName as is, without a path, and place the fileName next to your .java file. It will automatically be placed next to the generated .class files and - when packaged - in your .jar file.

OTHER TIPS

Just as owlstead commented keep in appropriate location and try like this

URL url = ClassLoader.getSystemResource(fileName);
br = new BufferedReader(new InputStreamReader(url.openStream()));

i.e keep the file in classes folder or bundle with jar or current working directory etc.

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