Ingila Ejaz
Ingila Ejaz

Reputation: 399

Is there any way to read a .txt file and make a 2d array of the contents in Java?

I want a JTable to be populated with certain information. That information (i.e the values stored in rows of the table) changes periodically. What I thought to implement it was storing the contents everytime the JTable is updated in a .txt file and then display that text file in a JTable.

Now my question is that is it a good approach? I mean if I store the contents of a text file into a JTable, when something is updated in the JTable, that updation will not be shown to the user unless they re-run the app (because a text file can't be read and written all at once).

Can anyone suggest me a good approach to it? The app needs to be real time so every time i.e I want the users to see the updated information dynamically while the app is running. I dont want them to close the app again and again to see the updated inofrmation. I'm using Java and linux.

Upvotes: 0

Views: 480

Answers (1)

Eric Robinson
Eric Robinson

Reputation: 2095

Here's another question on stack overflow that may help you out

Reading contents of a file into a 2D array

here's the code that reads a file into a 2D array

FileInputStream inputStream = new FileInputStream(fileName);
Scanner scanner = new Scanner(inputStream);
DataInputStream in = new DataInputStream(inputStream);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));

int lineCount = 0;
while ((line = bf.readLine()) != null)
{
    String[] numbers = line.split(" ");
    for ( int i = 0 ; i < 3 ; i++) 
         matrix[lineCount][i] = Double.parseDouble(numbers[i]);

    lineCount++;
}

bf.close();

Upvotes: 1

Related Questions