【问题标题】:How to read in a file of numbers into an array list in Java如何将数字文件读入Java中的数组列表
【发布时间】:2016-04-20 01:57:35
【问题描述】:

我希望能够从类似于以下内容的文件中读取地图:

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

并创建一个如下所示的数组列表:

{[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]}

我曾尝试使用 br.readLine(),但它似乎卡住了,但没有在中间抛出错误。

public static int[][] loadFile() 抛出 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;
    
}

【问题讨论】:

  • .... 而"error in the middle..." 是???
  • 它抛出Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0,因为您的fileArray 的长度为0,您不可能向其中添加任何新行/列
  • @HovercraftFullOfEels 我想你看错了,我神秘地没有收到任何错误,但是使用 print 语句告诉我程序只是停在 fileArray[j][i] = intArray[i];
  • @MadProgrammer 那么如果我使用数组列表,它应该可以工作吗?
  • 这表明您在某处有一个空的 catch 块

标签: java file-io


【解决方案1】:

基本问题是,您要声明一个长度为 0 的数组(无元素),这使得无法向其中添加任何元素。

int [][] fileArray = {};

除非您事先确切知道所需的行数/列数,否则数组并不是很有帮助,相反,您可以使用某种List,例如...

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);
}

我的“个人”直觉是根本不关心数组,而只是使用复合 Lists...

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();
}

【讨论】:

    【解决方案2】:

    Java 8 的魔法也是如此

    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)));
    

    输出

    [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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-26
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多