【问题标题】:How to read a single word (or line) from a text file Java?如何从文本文件 Java 中读取单个单词(或行)?
【发布时间】:2015-07-12 18:06:55
【问题描述】:

正如标题所说,我正在尝试编写一个程序,该程序可以从文本文件中读取单个单词并将它们存储到String 变量中。我知道如何使用FileReaderFileInputStream 来读取单个char,但我正在尝试这样做是行不通的。一旦我输入了单词,我就会尝试使用 .equals 将它们与我的程序中的其他字符串变量进行比较,所以如果我可以导入为字符串,那将是最好的。我也可以将文本文件中的一整行作为字符串输入,在这种情况下,我只在文件的每一行上放一个单词。如何从文本文件中输入单词并将它们存储到字符串变量中?

编辑: 好的,这种重复的帮助。它可能对我有用,但我的问题有点不同的原因是因为副本只告诉如何阅读单行。我试图阅读该行中的单个单词。所以基本上拆分行字符串。

【问题讨论】:

  • Read next word in java 的可能重复项
  • @EricLeibenguth 之类的,阅读上面的编辑
  • 不,不,仔细看看答案:下一行使用Scanner.nextLine(),下一个单词使用Scanner.next()

标签: java text io text-files inputstream


【解决方案1】:

这些都是非常复杂的答案。我相信它们都是有用的。但我更喜欢优雅简单 Scanner

public static void main(String[] args) throws Exception{
    Scanner sc = new Scanner(new File("fileName.txt"));
    while(sc.hasNext()){
        String s = sc.next();
        //.....
    }
}

【讨论】:

  • 是的,绝对同意,它们对我来说相当复杂。我基本上混合使用标记的重复问题的答案和@spork 的答案。不过感谢您的回答!
【解决方案2】:

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

【讨论】:

  • 好的,谢谢!这正是我想要的。
【解决方案3】:

你必须使用 StringTokenizer!这里是一个例子并阅读这个String Tokenizer

private BufferedReader innerReader; 
public void loadFile(Reader reader)
        throws IOException {
    if(reader == null)
    {
        throw new IllegalArgumentException("Reader not valid!");
    }
        this.innerReader = new BufferedReader(reader);
    String line;
    try
    {
    while((line = innerReader.readLine()) != null)
    {
        if (line == null || line.trim().isEmpty())
            throw new IllegalArgumentException(
                    "line empty");
        //StringTokenizer use delimiter for split string
        StringTokenizer tokenizer = new StringTokenizer(line, ","); //delimiter is ","
        if (tokenizer.countTokens() < 4)
            throw new IllegalArgumentException(
                    "Token number not valid (<= 4)");
        //You can change the delimiter if necessary, string example
        /*
        Hello / bye , hi
        */
        //reads up "/"
        String hello = tokenizer.nextToken("/").trim();
        //reads up ","
        String bye = tokenizer.nextToken(",").trim();
        //reads up to end of line
        String hi = tokenizer.nextToken("\n\r").trim();
        //if you have to read but do not know if there will be a next token do this
        while(tokenizer.hasMoreTokens())
        {
          String mayBe = tokenizer.nextToken(".");
        }
    }
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

【讨论】:

  • 好的,谢谢,我可能需要对这个 String Tokenizer 做一些研究,因为我以前从未见过它。几分钟后我会回到这个问题。
  • 我改了一些东西,希望对你有所帮助
  • 感谢@MicheleLacorte 的回答。这太好了,我肯定会调查这个,但现在 sporks 的答案更多的是我想要的,而且对我来说更容易理解(我还不是很好,哈哈)
【解决方案4】:

在 java8 中,您可以执行以下操作:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class Foo {
    public List<String> readFileIntoListOfWords() {
        try {
            return Files.readAllLines(Paths.get("somefile.txt"))
                .stream()
                .map(l -> l.split(" "))
                .flatMap(Arrays::stream)
                .collect(Collectors.toList());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }
}

虽然我怀疑拆分的参数可能需要更改,例如从单词末尾修剪标点符号

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    相关资源
    最近更新 更多