Home > Software design >  BufferedReader saving sentence, String array, then 2D int array
BufferedReader saving sentence, String array, then 2D int array

Time:01-01

I have a .txt file that contains text that I would like to save part of it in a String, part of it in a String array, and then the last part in a 2D int array, and am faced with two issues:

  1. How to read and save both of the arrays when their size is not known ahead of time?
  2. 2D array is not reading/saving properly

Here is the text file for reference:

This is the sentence to be read.
This
is
a
String
array.
90 47 110 95 95
101 87 
54 0 38 12 

Here is part of my method that is supposed to read and save the three data types:

BufferedReader br = new BufferedReader(new FileReader(fileName));
        
        sentence = br.readLine();

        stringArr = new String[5]; //how to initialize without set number of elements?
        for(int i = 0; i<stringArr.length; i  ){
            stringArr[i] = br.readLine();
        }

        int2DArr = new int[3][5]; //how to initialize with any amount of rows and columns?
        for(int i = 0; i<int2DArr.length; i  ){
            for(int j = 0; j<int2DArr[i].length; j  ){
                int2DArr[i][j] = br.read();
                //how to read the space after each int ?
            }
        }

How would I "grab" the size of the arrays by reading the text file, so that when I initialize both arrays, I have the proper sizes? Any help would be greatly appreciated!

CodePudding user response:

Instead of trying to achieve everything in a single pass we can pass through the file twice and obtain a neater code.

It will consume double time of course but it is going to help you understand how you could break bigger problems into smaller ones and deal with them one by one.

Here are the steps:

  1. Determine size of stringArr and intArr in first pass
  2. Fill value in respective array in second pass

If you are wondering how no of columns for int2DArr is determine. Simply we don't do it our self. We use the concept of Jagged Arrays

Read more here How do I create a jagged 2d array in Java?

import java.util.*;
import java.io.*;

class ReadFileIntoArr {
    public static void main(String args[]) throws IOException {
        String fileName = "test.txt";
        BufferedReader br = new BufferedReader(new FileReader(fileName));

        String line = br.readLine();
        int strSize = 0;
        int intSize = 0;
        boolean isDigit = false;

        while (line != null && line.trim().length() != 0) {
            if (!isDigit && Character.isDigit(line.charAt(0)))
                isDigit = true;
            if (isDigit)
                intSize  ;
            else
                strSize  ;
            line = br.readLine();
        }

        br = new BufferedReader(new FileReader(fileName));

        String[] stringArr = new String[strSize];
        for (int i = 0; i < stringArr.length; i  )
            stringArr[i] = br.readLine();

        int[][] int2DArr = new int[intSize][];
        for (int i = 0; i < int2DArr.length; i  )
            int2DArr[i] = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();

        System.out.println(Arrays.toString(stringArr));
        System.out.println(Arrays.deepToString(int2DArr));
    }
}

Note: In single pass this could be accomplished with the help of ArrayList and later transfer everything into respective array.

CodePudding user response:

Path path = Paths.get(fileName);
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());

String title = lines.get(0);
List<String> words = new ArrayList<>();
for (int i = 1; i < lines.size();   i) {
    String word = lines.get(i);
    if (!word.isEmpty() && Character.isDigit(word.codePointAt(0)) {
        break;
    }
    words.add(word);
}
String[] wordArray = words.toArray(new String[]);
int i0 = 1   words.size();
int n = lines.size() - i0;
int[][] numbers = new int[n][];
for (int i = i0; i < lines.size();   i) {
    String[] values = lines.get(i).trim().split("\\s ");
    int m = values.length;
    int[] row = new int[m];
    for (int j = 0; j < m;   m) {
        row[j] = Integer.parse(values[j]);
    }
    numbers[i - i0] = row;
}
  • Path is a generalisation of File, also URLs.
  • Files is a treasure trove of file functions.
  • One could do without dynamically sized List; one would need to test first, but normally one would use a List anyhow.
  • String.split splits on one or more whitespace.
  • Related