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

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

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

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

  • 如果扫描仪有下一行,则启动带有条件的while循环。即hasNextLine()在同时。

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

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

示例

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

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

After a successful journey of providing the best learning content at nhooo.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: nhooo.com 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 nhooo.com, 
you can learn at your own pace, in your own space. After a successful journey of providing the best 
learning content at nhooo.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.
猜你喜欢