2

我有一个项目,其部分目标是尽可能缩短代码。我已经尽我所能使它尽可能紧凑,但我想知道以下代码是否还有更多快捷方式

public static void read(String[] input) throws IOException {
    for (String s : input) {
        BufferedReader b = new BufferedReader(new FileReader(s)); 
        while (b.ready()) {
            String[] val = b.readLine().split(" ");
            for (String c : val) System.out.println(c);
        } 
        b.close();
    }   
}
4

2 回答 2

4

这取决于您所说的“紧凑”是什么意思。例如,您可以更改

String[] val = b.readLine().split(" ");
for (String c : val) System.out.println(c);

进入

for (String c : b.readLine().split(" ")) System.out.println(c);

或者使用使用Scanner类的不同方法,这将使您的代码更短且更具可读性。

public static void read(String[] input) throws IOException {
    for (String s : input) {
        Scanner scanner = new Scanner(new File(s));
        while (scanner.hasNext()) 
            System.out.println(scanner.next());
        scanner.close();
    }
}

您也可以尝试这种方式(基于Christian Fries回答的概念)

public static void read(String[] input) throws IOException {
    for (String s : input) 
        System.out.println(new Scanner(new File(s)).useDelimiter("\\Z").next().replace(' ', '\n'));
}

如您所见,这不会让您使用closeScanner,但由于File资源不是Closable您不必调用它的close方法,因此这种方法看起来很安全。

于 2013-11-04T20:55:36.917 回答
1

而不是使用split(" "),然后使用 for 循环在您可以使用的一行上打印结果数组的每个元素

System.out.println(b.readLine.replace(' ','\n'));

那是

public static void read(String[] input) throws IOException {
    for (String s : input) {
        BufferedReader b = new BufferedReader(new FileReader(s)); 
        while (b.ready()) System.out.println(b.readLine.replace(' ','\n'));
        b.close();
    }   
}
于 2013-11-04T21:01:13.280 回答