首页 > Java > java教程 > 正文

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

WBOY
发布: 2023-08-30 13:01:06
转载
1319 人浏览过

我们如何在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.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!