我们如何在 Java 中从文件内容创建一个字符串?


在 Java 中,你可以使用多种方法读取文件的内容,一种方法是使用 java.util.Scanner 类将其读取到字符串中,具体操作如下:

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

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

  • 启动一个 while 循环,条件为 Scanner 是否有下一行。即 while 中的 hasNextLine()

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

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

示例

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

Tutorials Point 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 Tutorials Point, you can learn at your own pace, 
in your own space.

After a successful journey of providing the best learning content at tutorialspoint.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: Tutorials Point 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 Tutorials Point, 
you can learn at your own pace, in your own space. After a successful journey of providing the best 
learning content at tutorialspoint.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.

更新于:2019 年 10 月 10 日

159 人次浏览

开启你的 职业生涯

完成课程后获得证书

开始吧
广告