Reading the contents of a text file

81 views Asked by At

I'm writing an application for displaying chrats. I'm using GWT Highcharts (by Moxie Group) to display the results. I add a random number to the chart and it works without a problem.

But I want to load numbers from a text file. I just want to read the contents of a file and put it on the array or something similar. How can I do this in Java?

1

There are 1 answers

3
N00b Pr0grammer On

You can use a small program as like the below to achieve that:

You may have to change the logic to read elements the way you want it for your GWT highcharts!

public class ReadATextFile {
    public static void main(String[] args) {
        try (RandomAccessFile readFile = new RandomAccessFile("C:\\Test.txt", "r");) {
            int EOF = (int) readFile.length();
            System.out.println("Length of the file is (" + EOF + ") bytes");
            //Considering to read the first 150 bytes out of 168 bytes on the file
            readFile.seek(0);
            byte[] bytes = new byte[EOF];

            readFile.readFully(bytes);
            readFile.close();

            System.out.println(new String(bytes));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

Where the Test.txt file's contents is something like this:

1 2 3 4
5 6 7 8
9 10 11