我有一个项目,部分目标是拥有尽可能短的代码。我已经做了我能想到的一切来使其尽可能紧凑,但我想知道以下代码是否还有更多快捷方式
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();
}
}
最佳答案
这取决于你所说的“紧凑”是什么意思。例如,您可以更改
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'));
}
如您所见,这不会让您关闭
扫描仪,但由于File
资源不是Closable
,因此您不必调用它的 close
方法,因此这种方法看起来很安全。
关于java - 有什么办法可以让这个更加紧凑吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19776835/