1. IO流读取
-
Inputstream
字节流按字节读取
-
Reader
字符流按字符读取
-
InputStreamReader
将字节流包装为字符流
-
BufferedReader
将InputStreamReader
包装实现逐行读取
public static List<String> getListFromfile(String file) {
List<String> wordList = new ArrayList<>();
try (InputStream inputStream = PyProcessService.class.getResourceAsStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
String word;
while ((word = reader.readLine()) != null) {
wordList.add(word.trim());
}
} catch (IOException e) {
e.printStackTrace();
}
return wordList;
}
2. Files.lines方法
-
Path
表示文件路径可以不用考虑不同平台路径分割符的差异
-
Files.lines
方法获得文件每行字符串构成的流,方便快捷
public static void main(String[] args) {
try (Stream<String> lines = Files.lines(Paths.get("./src/main/resources/suggest_words.csv"))) {
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}