[英]How to read a file that is located in the project folder java
使用 Eclipse,我在名为 HackGSU 的项目文件夹中有一个名为 bad_words.txt 的文件。 我想定位文件并读取文件的内容。 我看到了这个如何读取文本文件相对路径的答案,我试过这个:
private static String words[][] = new String[3][];
private static int ok = 17 + 2; //Add two for comment & empty line in text file
private static int med = 26 + 2; //Add two for comment & empty line in text file
private static int bad = 430 + 1; //Add one for comment in text file
private static String p = new File("").getAbsolutePath();
public static String[][] openFile() {
p.concat("/HackGSU/bad_words.txt");
//Set the a limit for the amount of words in each row
words[0] = new String[getOk()];
words[1] = new String[getMed()];
words[2] = new String[getBad()];
//Read the text file to add bad words to an array
try {
FileReader fr = new FileReader(p);
//Wrap file
BufferedReader br = new BufferedReader(fr);
//Add each line of file into the words array
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words[i].length; j++) {
try {
words[i][j] = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return words;
}
但我收到了这个回溯:
java.io.FileNotFoundException: C:\Users\nbrow_000\workspaceProjects\HackGSU (Access is denied)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at gsu.hack.harassment.BadWords.openFile(BadWords.java:28)
at gsu.hack.harassment.HarassFilter.<clinit>(HarassFilter.java:10)
at gsu.hack.harassment.CheckPercentage.main(CheckPercentage.java:20)
Exception in thread "main" java.lang.NullPointerException
at gsu.hack.harassment.HarassFilter.checkHarass(HarassFilter.java:23)
at gsu.hack.harassment.CheckPercentage.main(CheckPercentage.java:20)
我也这样回答如何使用 Java 直接从 Internet 读取文本文件? ,但我的 URL 构造函数有问题。
如果我把本地文件路径 (C://.../bad_words.txt) 它工作得很好,但我怎样才能让程序读取文件,以便如果我打包软件它仍然会找到正确的文件小路。
查看错误,您似乎没有获得完整路径。 代替
p.concat("/HackGSU/bad_words.txt");
尝试
p = p.concat("/HackGSU/bad_words.txt");
找出这个问题的答案,可能是您要寻找的!
如果您的资源已经在类路径中,则不需要对File
类使用相对路径。 您可以轻松地从类路径中获取它,例如:
java.net.URL url = getClass().getResource("bad_words.txt");
File file = new File(url.getPath());
甚至直接到输入流:
InputStream in = getClass().getResourceAsStream("bad_words.txt");
由于您有static
方法,请使用:
InputStream in = YourClass.class.getResourceAsStream("bad_words.txt");
此外,正如我在评论中已经提到的那样:
p.concat("/HackGSU/bad_words.txt");
不连接到p
而是返回一个新的连接字符串,因为字符串是不可变的。 只需使用: p+="/HackGSU/bad_words.txt"
代替
您可能应该使用反斜杠而不是斜杠:
p.concat("\HackGSU\bad_words.txt");
您也可以尝试键入双反斜杠:
p.concat("\\HackGSU\\bad_words.txt");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.