首页 > 解决方案 > 如何使用文件阅读器和字符数组拼凑字符串

问题描述

在另一个类中写了一个文件,现在我试图将文件拼凑成一个 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];

不工作

标签: javaarraysfile

解决方案


如果您的文件只包含一个字符串,那么有一种简单的方法可以读取它:

public String readMyFile( String fileName) throws IOException {

    Path path = Paths.get(fileName);

    return Files.readAllLines(path).get(0);
}

推荐阅读