如何使用Java从文件读取数据到String?

在Java中,您可以通过几种方式读取文件的内容,一种方式是使用java.util.Scanner类将其读取为字符串,为此,

  • 实例化 Scanner 类,将要读取的文件的路径作为其构造函数的参数。

  • 创建一个空的字符串缓冲区。

  • 如果 Scanner 有下一行,即hasNextLine()。则启动带有条件的while循环。

  • 在循环中,使用append()方法将文件的每一行附加到StringBuffer对象。

  • 使用toString()方法将缓冲区内容转换为String 。

在系统的C目录中创建一个名为sample.txt的文件,然后将以下内容复制并粘贴到其中。

nhooo.com is an E-learning company that set out on its journey to provide
knowledge to that class of readers that responds better to online content. With
nhooo.com, you can learn at your own pace, in your own space.

After a successful journey of providing the best learning content at
nhooo.com, we created our subscription based premium product called
Tutorix to provide Simply Easy Learning in the best personalized way for K-12
students, and aspirants of competitive exams like IIT/JEE and NEET.

以下Java程序将文件sample.txt的内容读入字符串并打印。

示例

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileToString {
   public static void main(String[] args) throws IOException {
      Scanner sc = new Scanner(new File("E://test//sample.txt"));
      String input;
      StringBuffer sb = new StringBuffer();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(" "+input);
      }
      System.out.println("Contents of the file are: "+sb.toString());
   }
}

输出结果

Contents of the file are: nhooo.com is an E-learning company that set out on its journey to provide
knowledge to that class of readers that responds better to online content. With nhooo.com, you can
learn at your own pace, in your own space. After a successful journey of providing the best learning content
at nhooo.com, we created our subscription based premium product called Tutorix to provide Simply
Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like
IIT/JEE and NEET.