首页 > Java > java教程 > 正文

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

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

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

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

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

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

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

    立即学习Java免费学习笔记(深入)”;

    一帧秒创
    一帧秒创

    基于秒创AIGC引擎的AI内容生成平台,图文转视频,无需剪辑,一键成片,零门槛创作视频。

    一帧秒创 41
    查看详情 一帧秒创
  • 在循环内使用 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中文网其它相关文章!

相关标签:
java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号