代码如下:
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方法会引发异常。 有什么我想念的吗?
答案 0 :(得分:1)
问题是,您的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());
}
}