>  기사  >  Java  >  Java의 파일 내용에서 문자열을 어떻게 만들 수 있나요?

Java의 파일 내용에서 문자열을 어떻게 만들 수 있나요?

WBOY
WBOY앞으로
2023-08-30 13:01:061296검색

Java의 파일 내용에서 문자열을 어떻게 만들 수 있나요?

Java에서는 다양한 방법으로 파일 내용을 읽을 수 있으며, 그 중 하나는 java.util.Scanner 클래스를 사용하여 파일 내용을 문자열로 읽는 것입니다. 이를 위해

  • instantiate Scanner 클래스를 생성하고 해당 생성자에 대한 매개변수로 읽을 파일의 경로를 사용합니다.

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

  • 스캐너에 다음 줄이 있으면 조건에 따라 while 루프를 시작합니다. 현재는 hasNextLine()입니다.

  • 루프 내에서 append() 메서드를 사용하세요.

  • 버퍼 내용을 문자열로 변환하려면 toString() 메서드를 사용하세요.

    li>

Sample

시스템 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제