从文件读取数据-Leetcode测试数据读取

在 IDE 中测试 leetcode 中的代码时,当输入数据规模比较大,如果直接赋值,会报 “代码过长“ 的错误,看网上的评论,似乎可以通过修改 IDE 的配置来解决该问题,但是主程序中放置超长的数据,非常的不优雅。因此,可以做一个从文件读取输入数据的转接。

主要涉及的知识点是从文件读取数据,针对 leetcode 问题:815.公交路线,主要的任务是将 文件中的数据读取到数组,相关的功能代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
数据示例:line1: 输入数组,routes; line2; source; line3: target
----
[[1,2,7],[3,6,7]]
1
6
----
将上述数据放置在 程序代码同级文件夹下,并命名:/src/data.txt
*/

String[] str = new String[3];
/**
step1: 从文件读取数据
主要是将文件中的内容放置到 String 数组中(如果是字节流,放置到 byte[] 数组中)
*/
try {
// method1(典型的方法): 使用 bufferedReader 包裹 FileReader
// BufferedReader in = new BufferedReader(new FileReader("src/data.txt"));

// method2: 直接使用 Files 类的静态方法进行读取
Path path = Paths.get("src/data.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for(int i = 0; i < 3; ++i){
str[i] = lines.get(i);
// str[i] = in.readLine(); // for method1
}
} catch (IOException e) {
e.printStackTrace();
}

/**
step2: 将文件读取到的数据转换为程序需要的数据类型。
主要是各种对 String 的操作
*/

// 处理 str[0], 数组数据。 使用 `},{` 进行split
// public String substring(int beginIndex, int endIndex), index 左包右不包
str[0] = str[0].substring(1, str[0].length()-2);
// split(String regex), 以 regex 匹配到的内容将 String 进行分割。regex 匹配的内容会被删除
String[] routesData = str[0].split("],");
int[][] routes = new int[routesData.length][];
for(int i = 0; i < routesData.length; ++i){
String[] routeData = routesData[i].substring(1).split(",");
int[] route = new int[routeData.length];
for(int j = 0; j < routeData.length; ++j){
route[j] = Integer.parseInt(routeData[j]);
}
routes[i] = route;
}
int source = Integer.parseInt(str[1]);
int target = Integer.parseInt(str[2]);