Amundeep Singh
Amundeep Singh

Reputation: 194

My program reads .txt files in Eclipse, but not when I export as .jar?

I have some .txt files in a folder called "progress" like this:

enter image description here

The program reads the files perfectly fine when I run it as a Java Application in Eclipse, but when I export it as a jar and run it, it doesn't work. I use BufferedReader to read the .txt files, and I refer to the text files as "progress/easy1.txt", etc. Is there something I could do to fix this?

EDIT:

I have a writer method like this:

public void writeToFile(String filename){

     BufferedWriter bufferedWriter = null;

     try {

            //Construct the BufferedWriter object
            bufferedWriter = new BufferedWriter(new FileWriter(filename));

            //Start writing to the output stream
            bufferedWriter.write("a");

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the BufferedWriter
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

}

So how would I incorporate the .getResourceAsStream() with this?

Upvotes: 0

Views: 752

Answers (2)

jenaiz
jenaiz

Reputation: 547

My class read a file from the root folder of my project using:

    FileInputStream fis = new FileInputStream(filename); 
    Scanner scanner = new Scanner(fis);

where filename is the name of my file (including the path of the file).

If you generate a runnable jar using eclipse selecting your class (with a main method), in my case testing.ReverseWords as "Launch Configuration" in the process and executing the jar like:

java -cp runnable.jar testing.ReverseWords progress/B-large-practice.in

and it find the file. I hope that help you.

Upvotes: 0

Francis Upton IV
Francis Upton IV

Reputation: 19443

Yes, you should put them in a directory within your source and access then using the classpath. See Class.getResourceAsStream() for example. This will make it work everywhere.

Upvotes: 2

Related Questions