有没有办法让这个更紧凑?

时间:2013-11-04 20:48:41

标签: java shorthand

我有一个项目,目标的一部分是尽可能使用最短的代码。我做了我能想到的一切,使其尽可能紧凑,但我想知道是否还有以下代码的快捷方式

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

2 个答案:

答案 0 :(得分: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'));
}

正如您所看到的,这不会让您close扫描程序,但由于File资源不是Closable,您不必调用其close方法,因此方法似乎很安全。

答案 1 :(得分: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();
    }   
}