java - 执行 jar 文件时出现 NoSuchFileException 错误
问题描述
我编写了一个读取文本文件的方法,当我运行它时它可以工作,但是当我执行 jar 时,我得到 NoSuchFileException 错误。这是我的代码:
private static final String textFile = "textFile.txt";
public readText() {
try {
regex = new String(Files.readAllBytes(Paths
.get(textFile)))
.replaceAll("\\r", "").split("\n");
} catch (final IOException e) {
e.printStackTrace();
}
}
有人能指出我哪里出错了或者我应该做些什么改变吗?
解决方案
我想出了一个办法:
try {
InputStream in = getClass().getResourceAsStream(textFile);
StringBuilder content = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
while(line!=null){
content.append(line).append(System.lineSeparator());
line = reader.readLine();
}
regex = content.toString()
.replaceAll("\\r", "").split("\n");
} catch (final IOException e) {
e.printStackTrace();
}
推荐阅读
- javascript - VueJS 中的计算属性清理
- embark - 运行登船演示将无法按预期工作
- serverless-framework - 如何在无服务器框架中将 RDS 代理设置为 lambda
- javascript - 获取结果数据 + Fetch 中的错误处理
- c# - 我如何组合或简化许多不同的方法,它们的作用只是一个字符串?
- c# - 如何使用从 UWP 中选择的日期/计算启动 Microsoft 默认日历和计算器?
- r - R 64 位版本在 Windows 10 上无响应(内幕版)
- python - 如何在python列表中打印上一行和下一行
- c++ - 在协议缓冲区中,如何在竞技场内“放置新”?
- postgresql - 使用 PostgreSQL 函数中的字符串生成唯一的字符串 ID