【发布时间】:2015-11-07 22:23:30
【问题描述】:
我知道这个问题以前经常被问到,但其他答案都没有对我有用。我正在尝试静态加载 .txt 文件。它在编译器 (Eclipse) 中运行良好,但在导出后出现 FileNotFound 异常。
我需要一个方法来接收文件路径并静态加载该 .txt 文件,并将该文件作为字符串返回。我想我必须对loadRecourceAsStream() 做点什么,但我不确定。
这是我现在的加载方式:
public static String getFilePath(String path) {
String line = null;
String file = "";
try {
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null){
file = file + line;
}
bufferedReader.close();
} catch(FileNotFoundException e) {
System.out.println("Unable to open file " + path + "\n");
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return file;
}
这是我尝试过的其他一些事情。它们都在编译器中工作,但在导出后不工作:
public static String loadFileAsString(String path){
StringBuilder builder = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while((line = br.readLine()) != null)
builder.append(line + "\n");
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path);
br.close();
}catch(IOException e){
e.printStackTrace();
}
return builder.toString();
}
还有:
public static String getFile(String path) {
Scanner controlBoard = new Scanner(System.in);
controlBoard = new Scanner(Utils.class.getResourceAsStream(path));
String file = controlBoard.nextLine();
file += "\n" + controlBoard.nextLine();
file += "\n" + controlBoard.nextLine();
return file;
}
还有:
public static String getFile(String path) {
System.out.println("test");
StringBuilder out = new StringBuilder();
try {
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = reader.readLine()) != null) {
out.append(line + "\n");
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return out.toString();
}
对我应该做什么有什么想法吗?
【问题讨论】:
-
你检查过创建的
.jar吗?它是否包含您尝试访问的文件?在 jar 内的哪个文件夹中?当您尝试使用 getResourceAsStream 时,这需要匹配您的代码 -
什么“导出后不起作用”?您遇到了哪些异常和/或错误? “不起作用”没有提供足够的信息让任何人在不胡思乱想的情况下帮助您。 “对我应该做什么有什么想法吗?”是的。首先提供有关无效的详细信息。
-
@Andrew Henle 正如我所说,一个 FileNotFoundException
-
@Marged 它在里面,位于 NameOfJar.jar/maps/Level1.txt。对路径执行 /maps/Level1.txt 仍然会导致错误。