我在将包含整数的文件存储到带有这些值的2d int数组时遇到问题。该文件具有以下格式:
1 19 36
1 4 212
1 2 732
2 9 111
2 1 66
2 12 29
2 19 14
2 17 65
3 2 17
3 11 38
3 14 122
3 17 211
3 1 390
3 18 78
3 9 11
4 3 273
4 5 29
4 12 42
5 4 122
5 16 12
注意某些行上有一些尾随空格。您可以查看完整文件here。
这是我到目前为止所拥有的。我读取文件并将每行放入数组列表中。我认为这会更容易,因为那时我只能解析整数并将它们放入二维数组中,但我一直有问题。有什么建议吗?
private void readRoadFile()
{
String line = null;
try
{
FileReader fr = new FileReader("road.dat");
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null)
{
roadInfo.add(line);
}
br.close();
} catch(FileNotFoundException e)
{
System.out.println("File does not exist");
} catch(IOException e)
{
System.out.println("Error reading file");
}
}
答案 0 :(得分:0)
你应该解析字符串并将你的arraylist转换为数组:
List<int[]> roadInfo = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("road.dat"))) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
String[] split = line.split("\t"); // or \\s+
int[] numbers = new int[split.length];
for (int i = 0; i < split.length; i++) {
numbers[i] = Integer.parseInt(split[i].trim());
}
roadInfo.add(numbers);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
int[][] twoDArray = roadInfo.toArray(new int[roadInfo.size()][]);
答案 1 :(得分:0)
您可以使用以下解决方案 - 它使用现代Java 8 Streams来简化数据流。
@Override
public void run()
{
List<List<Integer>> result = new ArrayList<>();
try (FileInputStream fileInputStream = new FileInputStream("stackoverflow-q-34096490.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader))
{
for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine())
result.add(Arrays.stream(line.split("\\s+")).filter(s -> !s.isEmpty()).map(Integer::parseInt).collect(Collectors.toList()));
} catch (IOException ioe)
{
System.err.println("Read failure!");
ioe.printStackTrace();
}
// use result
System.out.println(result);
}