Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để chúng ta tạo một chuỗi từ nội dung của một tệp trong java?

Trong Java, bạn có thể đọc nội dung của một tệp theo nhiều cách, một cách là đọc nó thành một chuỗi bằng cách sử dụng lớp java.util.Scanner, để làm như vậy,

  • Khởi tạo Máy quét lớp, với đường dẫn của tệp sẽ được đọc, như một tham số cho phương thức khởi tạo của nó.

  • Tạo bộ đệm chuỗi trống.

  • Bắt đầu một vòng lặp trong khi với điều kiện, nếu Máy quét có dòng tiếp theo. tức là hasNextLine () cùng lúc.

  • Trong vòng lặp, nối từng dòng của tệp vào đối tượng StringBuffer bằng cách sử dụng append () phương pháp.

  • Chuyển đổi nội dung của nội dung của bộ đệm thành Chuỗi bằng cách sử dụng toString () phương pháp.

Ví dụ

Tạo tệp có tên sample.txt trong thư mục C trong hệ thống của bạn, sao chép và dán nội dung sau vào đó.

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.

Chương trình Java sau đây đọc nội dung của tệp sample.txt vào một Chuỗi và in nó.

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());
   }
}

Đầu ra

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.