Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java의 파일 내용에서 문자열을 어떻게 생성합니까?

<시간/>

Java에서는 여러 가지 방법으로 파일의 내용을 읽을 수 있습니다. 한 가지 방법은 java.util.Scanner 클래스를 사용하여 문자열로 읽는 것입니다. 그렇게 하려면

  • 스캐너 인스턴스화 생성자에 대한 매개변수로 읽을 파일의 경로가 있는 클래스.

  • 빈 문자열 버퍼를 만듭니다.

  • 스캐너에 다음 줄이 있는 경우 조건으로 while 루프를 시작합니다. 즉, hasNextLine() 동안.

  • 루프 내에서 append()를 사용하여 파일의 각 줄을 StringBuffer 객체에 추가합니다. 방법.

  • toString()을 사용하여 버퍼 내용의 내용을 String으로 변환합니다. 방법.

예시

이름이 sample.txt인 파일 만들기 시스템의 C 디렉토리에서 다음 내용을 복사하여 붙여넣습니다.

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.