微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我们如何在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中从文件内容创建一个字符串?的详细内容,更多请关注编程之家其它相关文章

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐