Java - 使用 Scanner class 将 txt 文件的内容放入字符串中

Java - Put the content of a txt file in a String using Scanner class

我有一个示例 txt 文件:

This is an
example file.

我想使用 Scanner class 将此文件的内容放入字符串中。我按如下方式解决了这个问题:

try
{
    Scanner s = new Scanner(new File("example.txt"));
    String fileContent = new String();
    int i = 0;
    while(s.hasNextLine())
    {
        if(i !=0) 
        {
            fileContent += "\n";
        }
        fileContent += s.nextLine();
        i++;
    }
}
catch(FileNotFoundException e)
{

}

如果我没有把那行放在 if:

fileContent += "\n";

我会得到一个以 \n 开头的字符串,但这不是我想要的,因为我想在 fileContent 字符串中包含 相同的 文件内容.
有更好的方法来做我想做的事吗?使用扫描仪对我来说很重要 class。
谢谢!

像这样使用 else 块 -

while(s.hasNextLine()){

    if(i !=0){
        fileContent += "\n";
    }else{
       fileContent += s.nextLine();
    }
    i++;
 }  

它将删除 String 中的第一个换行符。

尝试类似的方法 如果您只需要一个字符串,您可以尝试类似的方法:

String content = s.useDelimiter("\Z").next();
System.out.println(content);