【发布时间】:2020-01-10 08:16:08
【问题描述】:
在另一个类中编写了一个文件,现在我试图将文件拼凑成一个 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];
没用
【问题讨论】:
-
我猜你的问题是因为 namePieces 没有初始化
-
您的错误表明
namePieces数组为空。我找不到您在您发布的代码中定义和初始化namePieces的位置。请edit您的帖子并添加namePieces的定义。 -
不要使用
char[]:当您阅读越来越多的数据时,您无法调整它的大小。使用StringBuilder,这几乎就是它的用途。