Search code examples
javareadfile

How to read a .txt file for each int on a line & storing to array?


public class assignment2
{
    public static void main(String[] args) throws IOException 
    {
        // TODO Auto-generated method stub
        FileInputStream fstream = new FileInputStream("assignment2.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        String strLine;

        //Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            // Print the content on the console
            System.out.println (strLine);
            String[] numbers = strLine.split(" ");
            System.out.print(numbers[1]);
        }
        //Close the input stream
        br.close();
    }
}

I expect that the code will print the String[] numbers as 1 0 10

I get this result 00371010

Please note that the input file is formatted as such:

1 0 10

2 0 9

3 3 5

4 7 4

5 10 6

6 10 7


Solution

  • You need to modify the code by adding another loop like this:

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        FileInputStream fstream = new FileInputStream("assignment2.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine;
    
        //Read File Line By Line
        while ((strLine = br.readLine()) != null){
            // Print the content on the console
            System.out.println (strLine);
            String[] numbers = strLine.split(" ");
            for (String num : numbers){
                System.out.print(num + " ");
            }
            System.out.println("\n");
        }
        //Close the input stream
        br.close();
    }
    

    Because, numbers[1] will only print the value at index 1.