繁体   English   中英

Java BufferedReader转换为字符串数组

[英]Java BufferedReader to String Array

我在这里检查了很多关于stackoverflow的不同主题,但到目前为止找不到任何有用的东西:/

所以这是我的问题。 我正在写文件复印机。 在读取文件时已经出现问题。 我的测试文档有3行随机文本。 所有这三行都应写入字符串数组中。 问题是只有textdocument的第二行被写入数组,而我不知道为什么。 已经调试过了,但是没有进一步了解我。

我知道对于具有不同类的文件复印机有不同的解决方案。但是我真的很想让它与我在这里使用的类一起运行。

    String[] array = new String[5];
    String datei = "test.txt";
    public String[] readfile() throws FileNotFoundException {
    FileReader fr = new FileReader(datei);
    BufferedReader bf = new BufferedReader(fr);
    try {
        int i=0;
        //String  Zeile = bf.readLine();
        while(bf.readLine() != null){
            array[i] = bf.readLine();
        //  System.out.println(array[i]);  This line is for testing
            i++;
        }
        bf.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return array;

对于循环的每次迭代,您都要调用readLine()两次,从而丢弃其他所有行。 您需要捕获每次readLine()调用返回的值,因为每个readLine()调用都会提高读取器在文件中的位置。

这是惯用的解决方案:

String line;
while((line = bf.readLine()) != null){
    array[i] = line;
    i++;
}

在这里您读了两行:

   while(bf.readLine() != null){
        array[i] = bf.readLine();
    //  System.out.println(array[i]);  This line is for testing
        i++;
    }

您必须将代码更改为:

   String line = null;
   while((line =bf.readLine()) != null){
        array[i] = line;
    //  System.out.println(array[i]);  This line is for testing
        i++;
    }

问题在这里:

while(bf.readLine() != null)

readLine()读取一行并在移至下一行的同时返回同一行。

因此,不仅要检查返回的值是否为null还要存储它。

String txt = null;
while((txt = bf.readLine()) != null)
    array[i++] = txt;

我认为是因为您两次调用readLine()。 第一次循环,然后第二次将其放入数组。 因此,它在循环的开头(第1行)读取一行,然后在循环中读取第一行代码(您看到的第2行)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM