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

WBOY
WBOY 转载
2023-08-30 13:01:06 969浏览

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

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

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

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

  • 如果扫描器有下一行,则根据条件启动 while 循环。即 hasNextLine() at while。

  • 在循环内使用 append() 方法。

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

    li>

示例

在系统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.

以上就是我们如何在Java中从文件内容创建一个字符串?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除