java - 如何使用文件阅读器和字符数组拼凑字符串
问题描述
在另一个类中写了一个文件,现在我试图将文件拼凑成一个 JLabel,所以我需要将文件中的名称转换为字符串。使用 FileReader 和一个 char 数组将每个字符分隔成一个数组,然后放在 JLabel 中。
我收到此错误NamePieces[x] = (char)nr;
:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at clients.initialize(clients.java:197)
at clients.<init>(clients.java:72)
这是我要读取文件的代码:
try(FileReader nameReader = new FileReader(NamePath)) {
int nr = nameReader.read();
int x = 0;
while(nr != -1) {
namePieces[x] = (char)nr;
nr = nameReader.read();
x++;
}
}
catch (FileNotFoundException e) {}
catch (IOException e1) {}
String name = String.valueOf(namePieces[0]) + namePieces[1];
不工作
解决方案
如果您的文件只包含一个字符串,那么有一种简单的方法可以读取它:
public String readMyFile( String fileName) throws IOException {
Path path = Paths.get(fileName);
return Files.readAllLines(path).get(0);
}
推荐阅读
- google-cloud-platform - 无法使用 Terraform 创建谷歌项目
- java - 使用 Spring JPA 加载更多功能
- html - 如何指定绝对路径?
- php - Laravel 日期格式和控制台
- python - 尽管已安装,但没有名为 import_export 的模块
- php - Laravel 策略自动检测
- html - 需要帮助将一些内容居中
- ibm-cloud - quotacheck:您的内核可能支持日志配额,但您没有使用它
- javascript - 循环内的 Firebase 实时数据库侦听器无法正常工作
- java - 为什么localhost中的script.js与根目录中的script.js不同