Shahar Kazaz
Shahar Kazaz

Reputation: 37

Jar can't access txt files

I'm pretty new to Java and I'm facing a problem that I can't find a solution for. I have written a program that reads and writes to a txt file. When I run it in NetBeans it seems to be working fine, but when I try to run the JAR file, it seems as if the program can't access the txt file.

I created the file using the following code :

File data = new File("src/data.txt");

Could the reason why it won't work be in the creation of the file? And if not what could it be?

EDIT: The text file is being modified as program advances, if I use the inputstream I won't be able to write to or change the txt file, should I change the way on which I'm managing my data? ( txt files) or is there a way for the jar to still have access to the Txt file?

Upvotes: 1

Views: 6741

Answers (2)

Shamim Ahmmed
Shamim Ahmmed

Reputation: 8383

Method 1: Where you are creating jar and running the program there is no such folder called "src" under the jar directory. You should create a folder called "src" in same directory of jar location. This will allow file write operation.

Method 2: If you want to keep the txt file inside the jar then you can use:

InputStream in = this.getClass().getClassLoader()
                            .getResourceAsStream("your package path/data.txt");

A complete example:

package com.file.loader;

public class Main {
    public static void main(String[] args) throws IOException {
    InputStream in = Main.class.getClassLoader().getResourceAsStream(
            "com/file/loader/data.txt");
    }
}

Upvotes: 5

Reimeus
Reimeus

Reputation: 159754

This statement

File data = new File("src/data.txt");

relys on the file being present in the file system. You need to read the file as a resource so that the JAR file can be run independently of the text file

InputStream input = getClass().getResourceAsStream("/path/to/data.txt");

Edit:

I suggest using the strategy of storing the the text file in as a "default", then when changes are required, write a new file under "user.home". Check the existence of the modified file before reading any data.

Upvotes: 7

Related Questions