gpt4 book ai didi

java - 有什么办法可以使它更紧凑吗?

转载 作者:行者123 更新时间:2023-11-30 06:21:59 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com