Skip to content
Advertisement

BufferedReader saving sentence, String array, then 2D int array

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!

Advertisement

Answer

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.

Update: After understanding the constraints for your problem here is another version

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 && 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] = convertStringArrToIntArr(br.readLine().split(" "));

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

    public static boolean isDigit(char c) {
        return c >= '0' && c <= '9';
    }

    public static int[] convertStringArrToIntArr(String[] strArr) {
        int[] intArr = new int[strArr.length];
        for (int i = 0; i < strArr.length; i++)
            intArr[i] = Integer.parseInt(strArr[i]);
        return intArr;
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement