Java – Reading text from file and storing each word from every line into separate variables

file-iojava

I have a .txt file with the following content:

1 1111 47
2 2222 92
3 3333 81

I would like to read line-by-line and store each word into different variables.

For example: When I read the first line "1 1111 47", I would like store the first word "1" into var_1, "1111" into var_2, and "47" into var_3. Then, when it goes to the next line, the values should be stored into the same var_1, var_2 and var_3 variables respectively.

My initial approach is as follows:

import java.io.*;
class ReadFromFile
{
    public static void main(String[] args) throws IOException
    {
        int i;
        FileInputStream fin;
        try
        {
            fin = new FileInputStream(args[0]);
        }
        catch(FileNotFoundException fex)
        {
            System.out.println("File not found");
            return;
        }
        do 
        {
            i = fin.read();
            if(i != -1) 
                System.out.print((char) i);
        } while(i != -1);

        fin.close();
    }
}

Kindly give me your suggestions. Thank You

Best Solution

public static void main(String[] args) throws IOException {
    File file = new File("/path/to/InputFile");
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    String line = null;
    while( (line = br.readLine())!= null ){
        // \\s+ means any number of whitespaces between tokens
        String [] tokens = line.split("\\s+");
        String var_1 = tokens[0];
        String var_2 = tokens[1];
        String var_3 = tokens[2];
    }
}