简体   繁体   中英

How to read in a file of numbers into an array list in Java

I want to be able to read in a map from a file that looks something like:

0, 0, 0, 0, 0

0, 0, 1, 0, 0

0, 1, 1, 1, 1

0, 1, 1, 1, 0

0, 0, 1, 1, 0

And create an array list that looks like:

{[0, 0, 0, 0, 0],

[0, 0, 1, 0, 0],

[0, 1, 1, 1, 1],

[0, 1, 1, 1, 0],

[0, 0, 1, 1, 0]}

I have tried using br.readLine() but it appears to be getting stuck but not throwing an error in the middle.

public static int[][] loadFile() throws IOException{

  FileReader in = new FileReader(Main.currentFilePath + Main.currentFile); BufferedReader br = new BufferedReader(in); String line; int [] intArray = {}; int [][] fileArray = {}; int j = 0; while ((line = br.readLine()) != null) { List<String> stringList = new ArrayList<String>(Arrays.asList(line.split(","))); String[] stringArray = stringList.toArray(new String[0]); List<Integer> intList = new ArrayList<Integer>(); System.out.println("RRRRR"); for(int i = 0; i < stringList.size(); i++) { Scanner scanner = new Scanner(stringArray[i]); System.out.println("GGGGG"); while (scanner.hasNextInt()) { intList.add(scanner.nextInt()); intArray = intList.parallelStream().mapToInt(Integer::intValue).toArray(); System.out.println("FFFF"); } System.out.println(fileArray[j][i]); fileArray[j][i] = intArray[i]; } j++; } return fileArray; } 

The basic problem is, you're declaring an array of 0 length (no elements), which makes it impossible to add any elements to it.

int [][] fileArray = {};

Unless you know in advance EXACTLY the number of rows/columns you need, arrays are not very helpful, instead, you could make use of a List of some kind, for example...

List<int[]> rows = new ArrayList<>(5);
int maxCols = 0;
try (BufferedReader br = new BufferedReader(new FileReader(new File("Test.txt")))) {
    String text = null;
    while ((text = br.readLine()) != null) {
        System.out.println(text);
        String[] parts = text.split(",");
        int[] row = new int[parts.length];
        maxCols = Math.max(maxCols, row.length);
        for (int col = 0; col < parts.length; col++) {
            row[col] = Integer.parseInt(parts[col].trim());
        }
        rows.add(row);
    }
} catch (IOException ex) {
    ex.printStackTrace();
}

int[][] map = new int[rows.size()][maxCols];
for (int row = 0; row < rows.size(); row++) {
    map[row] = rows.get(row);
}

My "personal" gut feeling is simply not to bother with the arrays at all and simply make use of compound List s...

List<List<Integer>> rows = new ArrayList<>(5);
try (BufferedReader br = new BufferedReader(new FileReader(new File("Test.txt")))) {
    String text = null;
    while ((text = br.readLine()) != null) {
        System.out.println(text);
        String[] parts = text.split(",");
        List<Integer> row = new ArrayList<>(parts.length);
        for (String value : parts) {
            row.add(Integer.parseInt(value.trim()));
        }
        rows.add(row);
    }
} catch (IOException ex) {
    ex.printStackTrace();
}

Here's the same with Java 8 magic

String filePath = "input.txt";
List<Integer[]> output = new ArrayList<>();

try(Stream<String> stream = Files.lines(Paths.get(filePath)) ) {

    stream.filter(line -> line != null && !line.isEmpty())
    .forEach(line->output.add(
        Arrays.stream(line.split(", "))//assuming that 2 numbers are separated by a comma followed by a white space
        .map(Integer::parseInt)
        .toArray(size -> new Integer[size])
    ));

} catch(Exception ex) {
    ex.printStackTrace();
}

output.forEach(s -> System.out.println(Arrays.toString(s)));

Output

[0, 0, 0, 0, 0]
[0, 0, 1, 0, 0]
[0, 1, 1, 1, 1]
[0, 1, 1, 1, 0]
[0, 0, 1, 1, 0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM