gpt4 book ai didi

java - 未处理异常的看似虚假的错误消息

转载 作者:行者123 更新时间:2023-12-02 09:57:14 24 4
gpt4 key购买 nike

这是代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.stream.Collectors;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.List;
public class CSVIO
{
//read a file and return a list of records in the file
public static List<String[]> read(File f) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(f));
List<String[]> out = br.lines()
.map( e -> e.split(","))
.collect(Collectors.toList());
return out;

}
//write from a list of recrords into CSV format
public static void write(List<String[]> items, File dest) throws IOException
{
//return true if it successfully writes.
final BufferedWriter bw = new BufferedWriter(new FileWriter(dest));
items.stream()
.map( row -> String.join(",", row))
.forEach( row -> bw.write(row + "\n"));
}
}

运行时收到此错误消息:

$ javac CSVIO.java
CSVIO.java:29: error: unreported exception IOException; must be caught or declared to be thrown
.forEach( row -> bw.write(row + "\n"));
^
1 error

我已经正确声明 write 方法抛出异常。我有什么遗漏的吗?

最佳答案

问题是,您的 br.write() 抛出异常。您必须在 lambda 表达式中捕获这一点 (.forEach()):

items.stream()
.map(row -> String.join(",", row))
.forEach( row -> {
try {
bw.write(row + "\n");
} catch (IOException e) {
e.printStackTrace();
}
});

但是您可以使用 Files.write() 来缩短它:

public static void write(List<String[]> items, Path path) throws IOException {
List<String> lines = items.stream()
.map(row -> String.join(",", row))
.collect(Collectors.toList());
Files.write(path, lines);
}

您还可以使用 Files.lines() 简化您的 read 方法:

public static List<String[]> read(Path path) throws IOException {
try (Stream<String> lines = Files.lines(path)) {
return lines
.map(e -> e.split(","))
.collect(Collectors.toList());
}
}

关于java - 未处理异常的看似虚假的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55909641/

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