프로그래머는 파일 읽기 및 쓰기가 필요한 Java 애플리케이션으로 작업하는 동안 Java에서 텍스트 파일을 사용합니다. 텍스트 파일은 정보, 코드 또는 기타 데이터를 저장하는 보편적인 방법입니다. 텍스트 파일은 가로로 구성된 일련의 문자로 간주됩니다. Java의 텍스트 파일에는 Java 코드가 포함된 .java와 같은 확장자가 있습니다. Java는 일반 텍스트 파일을 읽거나 쓰는 방식으로 처리할 수 있는 다양한 유틸리티를 제공합니다. 이해에 따라 읽기/쓰기 유틸리티를 선택할 수 있습니다.
주요 하이라이트
- 텍스트 파일은 다양한 문자로 구성되며 java.io.package를 사용하여 읽기 및 쓰기 작업을 수행할 수 있습니다.
- 읽으려면 Reader 클래스나 유틸리티 클래스를 사용할 수 있습니다. 일부 유틸리티 클래스는 File Class, FileReader, BufferedReader 및 Scanner 클래스입니다.
- Java에서 파일에 쓰려면 Java 7 Files, FileWriter, BufferedWriter 및 FileOutputStream을 사용할 수 있습니다.
- 다양한 방법을 사용하면 Java에서 텍스트 파일을 효율적으로 처리할 수 있습니다.
Java에서 텍스트 파일을 읽는 방법은 무엇입니까?
- 텍스트 파일의 각 줄에는 일반 문자가 있으며, 각 줄은 특정 줄의 끝을 나타내는 보이지 않는 '줄 끝' 기호로 표시됩니다.
- Java에서 텍스트 파일을 읽으려면 다양한 유틸리티를 사용할 수 있습니다. 각 유틸리티에는 텍스트 파일을 읽는 방법이 있으며 다른 유틸리티와는 다른 일부 기능을 제공합니다.
- 이해를 돕기 위해 다양한 방법을 좋은 예와 함께 설명하겠습니다.
방법을 시작하기 전에 "/Users/praashibansal/Desktop/Data/test.txt" 경로에 "Hello, there"라는 내용이 포함된 텍스트 파일 "test.txt"를 고려하고 있습니다.
광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사방법 1 – BufferedReader 클래스 사용
- 이 방법을 사용하여 문자 입력 스트림에서 텍스트를 읽을 수 있습니다. 기본 버퍼 크기(8KB)를 사용하거나 직접 지정할 수 있습니다. 인코딩을 지원합니다.
- 각 요청에는 기본 문자 스트림 또는 바이트 스트림으로 구성된 읽기 요청을 생성하는 리더가 있습니다.
- 따라서 많은 개발자는 읽기() 작업을 사용하여 모든 리더 주위에 BufferedReader를 래핑하는 것을 권장합니다.
- 대용량 파일 처리에 적합합니다. 이 방법은 동기화되므로 여러 스레드에서 사용할 수 있습니다.
코드:
import java.io.*; public class BReader { public static void main(String[] args) throws Exception { File f = new File( "https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); // Creating an object BufferedReader b = new BufferedReader(new FileReader(f)); // Declaring a string variable String s; // Condition holds till // there is a character in a string while ((s = b.readLine()) != null) // Print the string System.out.println(s); } }
출력:
방법 2 – FileReader 클래스 사용
- FileReader를 사용하여 BufferedReader를 가져와 파일 읽기를 시작할 수 있습니다.
- BufferedReader와 달리 인코딩을 지원하지 않고 대신 시스템의 기본 인코딩을 사용합니다.
- 단지 문자를 읽는 간단한 방법입니다.
- 이 클래스는 세 개의 생성자를 사용합니다.
- FileReader(파일 파일): 새로운 FileReader를 생성합니다. 파일은 콘텐츠를 읽을 파일입니다.
- FileReader(FileDescriptor fd): FileDescriptor로 지정된 파일에서 읽는 새 FileReader를 생성합니다.
- FileReader(String fileName): fileName이라는 파일에서 읽을 새 FileReader를 생성합니다.
코드:
import java.io.*; public class RFile { public static void main(String[] args) throws Exception { // Passing the file’s path FileReader f = new FileReader( "https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); // declaring loop variable int i; while ((i = f.read()) != -1) // Print the content of a file System.out.print((char)i); } }
출력:
방법 3 - 스캐너 클래스 사용
- 간단한 텍스트 스캐너이며 정규식을 통해 기본 유형과 문자열을 구문 분석할 수 있습니다.
- 구분자 패턴을 통해 입력을 토큰으로 나눕니다. 기본적으로 구분 기호는 공백입니다.
- 그런 다음 토큰은 다양한 유형의 값으로 변환됩니다.
코드:
import java.io.File; import java.util.Scanner; public class ReadScan { public static void main(String[] args) throws Exception { // passing the file’s path File file = new File("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); Scanner s = new Scanner(file); while (s.hasNextLine()) System.out.println(s.nextLine()); } }
출력:
방법 4 - Files 클래스 방법 사용
- Files 클래스는 파일을 읽기 위해 다음 방법을 사용합니다.
- readAllBytes(Path path): 파일에서 모든 바이트를 읽고 파일의 바이트가 포함된 바이트 배열을 반환합니다.
- readAllLines(Path path, Charsetcs): 파일의 모든 줄을 읽고 파일의 줄이 포함된 목록을 반환합니다.
코드:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FCExample { public static void main(String[] args) { Path path = Paths.get("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); try { byte[] b = Files.readAllBytes(path); System.out.println("Read bytes: \n"+new String(b)); } catch (IOException e) { } } }
출력:
How to Write a Text File in Java?
- Writing a text file in Java is also a simple process. Java offers different utilities to help write the lines to the file.
- Now for this process, we are assuming a file at the location- C:\\Users\\Data\\Desktop\\write.txt to which we are writing.
Method 1 – Using FileWriter Method
- This all-in-one method allows you to write int, byte array, and String to the File.
- It allows you to write directly into Files and is used in case of the less writes.
- Using the FileWriter method, you can write part of the String or byte array.
Code:
import java.io.FileWriter; public class FWFile { public static void main(String args[]){ try{ FileWriter f=new FileWriter("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); f.write("Hello"); f.close(); } catch(Exception e) { System.out.println(e); } System.out.println("Hello"); } }
Output:
Method 2 – Using BufferedWriter Method
- BufferedWriter is similar to FileWriter, but BufferedWriter uses an internal buffer to write data into File.
- It works well if you need to do more write operations and to ensure performance.
Code:
import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; public class BRExample { public static void main(String args[]) { String data = "data for output file"; try { // Creates a FileWriter FileWriter file = new FileWriter("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); try ( // Creates a BufferedWriter var o = new BufferedWriter(file)) { // Writes the string to the file o.write(data); } } catch (IOException e) { e.getStackTrace(); } } }
Output:
Method 3 – Using FileOutputStream Method
- For writing text to the file, you can simply use FileWriter and BufferedWriter.
- But, if you want the raw stream data to be written directly into a file, it is recommended to use the FileOutputStream utility.
- With this method, you must create the class object with the specific filename to write data into a file.
- The following example converts the string content into the byte array we will write into the file using the write() method.
Code:
import java.io.FileOutputStream; import java.io.IOException; public class GFG { public static void main(String[] args) { String f = "Hello"; FileOutputStream o = null; // starting Try block try { // creating an object of FileOutputStream o = new FileOutputStream("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); // storing byte content from string byte[] str = f.getBytes(); // writing into the file o.write(str); // printing success message System.out.print( "data added successfully."); } // Catch block for exception handling catch (IOException e) { System.out.print(e.getMessage()); } finally { // closing the object if (o != null) { // checking if the file is closed try { o.close(); } catch (IOException e) { // showing exception message System.out.print(e.getMessage()); } } } } }
Output:
Method 4 – Using Files Class
- In Java 7, you will get another utility, Files class, allowing you to write to a text file using its write function.
- Internally, this class uses the OutputStream utility to write a byte array into the file.
Code:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Java Files write file example * * @author pankaj * */ public class FCExample { public static void main(String[] args) { Path path = Paths.get("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); try { String str = "Example"; byte[] bs = str.getBytes(); Path w = Files.write(path, bs); System.out.println("Written content in file:\n"+ new String(Files.readAllBytes(w))); } catch (IOException e) { } } }
Output:
Conclusion
Reading and writing a file in Java is a straightforward process. With the availability of different methods and utilities in Java, you can choose a specific way to read from and write to a file. Each utility has its functionality that makes it different from others.
FAQs
Q1. What are the different methods to read a text file in Java?
Answer: To read, you can use Reader Class or utility class. Some utility classes are- File Class, FileReader, BufferedReader, and Scanner class.
Q2. What are the different methods for writing a text file in Java?
Answer: To write a file in Java, you can use FileWriter, BufferedWriter, java 7 Files, FileOutputStream, and many other methods.
Q3. What package to use for handling files in Java?
Answer: You can easily import the File class from the java.io package to work with files.
위 내용은 Java의 텍스트 파일의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

Dreamweaver Mac版
시각적 웹 개발 도구

WebStorm Mac 버전
유용한 JavaScript 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.
