Search code examples
javafilearraylistio

Very strange File reading output Java


So, I read words from an text file and save them in an ArrayList of ArrayLists. It should print the words exactly as they are in the file. For example:

test1 test2 test3 test4 test5
test6 test7 test8
test9 test10

But it prints this: Actual output here Why does it behave like that and how to fix it? Here is the reading code:

package com.company;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;

public class WordOrder {
    public ArrayList<ArrayList<String>> LinesList;
    public ArrayList<String> Words_per_line_list;
    protected String FileName;
    protected File file;
    public WordOrder(){
        LinesList = new ArrayList<>();
        Words_per_line_list = new ArrayList<>();
    }
public void wordReading() throws IOException, IndexOutOfBoundsException{
        String word_to_be_read;
            Scanner scan = new Scanner (System.in);
            System.out.println ("Enter the name of the file");
            FileName = scan.nextLine ();
            file = new File(FileName);
            BufferedReader in = new BufferedReader(new FileReader (FileName));
            if(in.read () == -1){
                throw new IOException ("File does not exist or cannot be accessed");
            }
            System.out.println ("Test");
            int i =0, j = 0;
            while(in.readLine() != null) {
                LinesList.add(i, Words_per_line_list);
                while ((in.read ()) != -1) {
                    word_to_be_read = in.readLine ();
                    Words_per_line_list.add(j, word_to_be_read);
                    System.out.println (LinesList.get (i).get (j));
                    j++;
                }
                i++;
            }
    }

Any help would be appreciated.


Solution

  • The while statements are reading data, but you're not doing anything with that data..

    The first while(in.readLine() != null) { will read the first line from your file

    i.e. test1 test2 test3 test4 test5

    but you don't do anything with it.

    the second while ((in.read ()) != -1) { will read a single character from the file. So the t leaving est6 test7 test8 to be read by word_to_be_read = in.readLine ();, then again the t from the next line, leaving est9 test10 for the next readline

    You can read the line into a variable in the outer while, then just process the line however you need to inside the while loop.

    String line;
    while((line = in.readLine()) != null) {
        // process the line however you need to
        System.out.println(line);
    }