Jar无法访问txt文件 [英] Jar can't access txt files
问题描述
我是Java的新手,我遇到了一个无法找到解决方案的问题。
我编写了一个读取和写入txt文件的程序。当我在NetBeans中运行它似乎工作正常,但是当我尝试运行JAR文件时,似乎程序无法访问txt文件。
<我使用以下代码创建了该文件:
文件数据=新文件(src / data.txt);
可能之所以无法创建文件?如果不是它可能是什么?
编辑:
文本文件正在被修改为程序前进,如果我使用输入流我将无法要写入或更改txt文件,我应该更改我管理数据的方式吗? (txt文件)或jar有没有办法访问Txt文件?
方法1:在创建jar并运行程序的地方,jar目录下没有名为src的文件夹。您应该在jar位置的同一目录中创建一个名为src的文件夹。这将允许文件写入操作。
方法2:如果你想将txt文件保存在jar中,那么你可以使用:
InputStream in = this.getClass()。getClassLoader()
.getResourceAsStream(your package path / data.txt );
一个完整的例子:
package com.file.loader;
公共类Main {
public static void main(String [] args)抛出IOException {
InputStream in = Main.class.getClassLoader()。getResourceAsStream(
COM /文件/装载器/ data.txt中);
}
}
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?
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");
}
}
这篇关于Jar无法访问txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!