简体   繁体   中英

Java BufferedReader to String Array

I was looking through a lot of diffrent subjects here on stackoverflow but couldn't find anything helpful so far :/

So this is my problem. I am writing a filecopier. The problem occurs already at reading the file. My test docoument got 3 lines of random text. All those 3 lines should get written in a string array. The problem is that only the 2nd line of the textdocument gets written in the array and I can't figure out why. Already debugged it, but didn't get me any further.

I know there are diffrent solutions for a filecopier with diffrent classes etc. But I would really like to get it running with the classes I used here.

    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;

You're calling readLine() twice for each iteration of the loop, thereby discarding every other line. You need to capture the value returned by every call to readLine() , because each readLine() call advances the reader's position in the file.

Here's the idiomatic solution:

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

Here you read 2 lines:

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

You have to change your Code to:

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

The problem is here :

while(bf.readLine() != null)

readLine() reads a line and returns the same at the same time it moves to the next line.

So instead of just checking if the returned value was null also store it.

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

I think its because you are calling readLine() twice. First time in the loop, and then second time when you put it in the array. So, it reads a line at the beginning of the loop (line 1), then first line of code inside the loop (line 2 that you see)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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