【问题标题】:How to piece together String using file reader and char array如何使用文件阅读器和字符数组拼凑字符串
【发布时间】: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,这几乎就是它的用途。

标签: java arrays file


【解决方案1】:

您的问题很可能是因为namePieces 未初始化。正如 cmets 中已经提到的,您不应该使用 char[] 作为角色的容器(因为在现实世界中,您不会每次都知道文件内容的长度,因此您可能需要调整容器的大小),使用Java标准库提供的StringBuilder会更好。它将保护您免于越界。

StringBuilder namePieces = new StringBuilder();
File file = new File(filePath);
BufferedReader reader = new BufferedReader(
                            new InputStreamReader(new FileInputStream(file),
                                                  Charset.forName("UTF-8")));
int c;
while((c = reader.read()) != -1) {
    namePieces.append((char) c);
}

String nameString = namePieces.toString(); // Use this string as a complete array of needed characters

如您所见,我改变了一种方法,不仅使用了StringBuilder,还使用了BufferedReader。但是,对于您的任务,您可以保留 FileReader 原样。只需考虑将字符附加到构建器。

【讨论】:

    【解决方案2】:

    如果您的文件只包含一个字符串,则有一种直接的读取方法:

    public String readMyFile( String fileName) throws IOException {
    
        Path path = Paths.get(fileName);
    
        return Files.readAllLines(path).get(0);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 2021-10-30
      • 2012-06-10
      • 2018-02-06
      • 1970-01-01
      相关资源
      最近更新 更多