要从文本文件中读取行,可以使用以下命令(使用try-with-resources):
String line;try ( InputStream fis = new FileInputStream("the_file_name"); InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr);) { while ((line = br.readLine()) != null) { // Do your thing with line }}
同一事物的更紧凑,更易读的版本:
String line;try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("the_file_name"), Charset.forName("UTF-8")))) { while ((line = br.readLine()) != null) { // Do your thing with line }}
要将一行大块成单个单词,可以使用String.split:
while ((line = br.readLine()) != null) { String[] words = line.split(" "); // Now you have a String array containing each word in the current line}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)