如何从文本文件Java中读取单个单词(或一行)?

如何从文本文件Java中读取单个单词(或一行)?,第1张

如何从文本文件Java中读取单个单词(或一行)?

要从文本文件中读取行,可以使用以下命令(使用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}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5498619.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存