Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...