【发布时间】:2020-04-20 18:10:15
【问题描述】:
我想从 Java 中读取文件。复杂之处在于将其管理到自己的二维数组中。 文件如下:
# 1 1 1 2 1 3 1 4 1 5 2 3 8 8 9 7 18 17
* 2 4 2 5 2 6 2 7 2 8 18 18 10 11 16 18
HRow 5 5 20 3
VRow 6 6 10 4
空格是对之间的分隔符。对内有 2 个空格,对之间有 3 个空格。
输出应该是:
private static final int[][] HASH_LOCATIONS = {{1,1},{1,2},{1,3},{1,4},{1,5},{2, 3}, {8, 8}, {9, 7}, {17, 18}};
private static final int[][] AST_LOCATIONS = {{2, 4}, {2, 5}, {2, 6}, {2, 7}, {2, 8}, {18, 18}, {10, 11}, {16, 18}};
private static final int [][] H_ROW = {{5,5,20,3}};
private static final int [][] V_ROW = {{6,6,10,4}};
我尝试了以下方法:
try {
FileInputStream fileIn = new FileInputStream(fileName);
Scanner scanner = new Scanner(fileIn);
while (scanner.hasNext()){
String itemType = scanner.next();
if (itemType.equals("#")) {
ArrayList<Integer> hashLocations = new ArrayList<>();
while(scanner.hasNextInt()){
hashLocations.add(scanner.nextInt());
}
} else if (itemType.equals("*")) {
ArrayList<Integer> astLocations = new ArrayList<>();
while(scanner.hasNextInt()){
astLocations.add(scanner.nextInt());
}
} else if (itemType.equals("HRow")) {
ArrayList<Integer> hLocations = new ArrayList<>();
while(scanner.hasNextInt()){
hLocations.add(scanner.nextInt());
}
} else if (itemType.equals("VRow")) {
ArrayList<Integer> vLocations = new ArrayList<>();
while(scanner.hasNextInt()){
vLocations.add(scanner.nextInt());
}
}
}
return true;
} catch (FileNotFoundException ex) {
return false;
}
我不确定如何管理。任何帮助,将不胜感激。
【问题讨论】:
标签: java file multidimensional-array java.util.scanner