class CsvReader {
private static final String SEPARATOR = ";";
private final Reader source;
CsvReader(Reader source) {
this(source);
}
List<String> readHeader() {
try (BufferedReader reader = new BufferedReader(source)) {
return readerlines()
findFirst()
map(line -> ArraysasList(linesplit(SEPARATOR)))
get();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
相当简单,自我解释型的。类似的,创建了一个方法来读取所有的记录。读取记录的算法如下:
打开资源文件进行读取
跳过首行
用分隔符分割行。
对每行应用一个map *** 作,将行映射到一个字符串列表
下面是它的实现:
class CsvReader {
List<List<String>> readRecords() {
try (BufferedReader reader = new BufferedReader(source)) {
return readerlines()
substream(1)
map(line -> ArraysasList(linesplit(separator)))
collect(CollectorstoList());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
会注意到两个方法中的map是几乎一样的。事实上,它可以提取到一个变量里面:
Function<String, List<String>> mapper
= line -> ArraysasList(linesplit(separator));
我写了个测试来完成整个过程。
public class CsvReaderTest {
@Test
public void readsHeader() {
CsvReader csvReader = createCsvReader();
List<String> header = csvReaderreadHeader();
assertThat(header)
contains("username")
contains("visited")
hasSize(2);
}
@Test
public void readsRecords() {
CsvReader csvReader = createCsvReader();
List<List<String>> records = csvReaderreadRecords();
assertThat(records)
contains(ArraysasList("jdoe", "10"))
contains(ArraysasList("kolorobot", "4"))
hasSize(2);
}
private CsvReader createCsvReader() {
try {
Path path = Pathsget("src/test/resources", "samplecsv");
Reader reader = FilesnewBufferedReader(
path, CharsetforName("UTF-8"));
return new CsvReader(reader);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}调用外部接口要看外部什么接口,一般来说外部现在基本都>>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)