프로그래머는 파일 읽기 및 쓰기가 필요한 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는 플랫폼 별 문제를 어떻게 완화합니까? Java는 JVM 및 표준 라이브러리를 통해 플랫폼 독립성을 구현합니다. 1) Bytecode 및 JVM을 사용하여 운영 체제 차이를 추상화합니다. 2) 표준 라이브러리는 Paths 클래스 처리 파일 경로 및 Charset 클래스 처리 문자 인코딩과 같은 크로스 플랫폼 API를 제공합니다. 3) 최적화 및 디버깅을 위해 실제 프로젝트에서 구성 파일 및 다중 플랫폼 테스트를 사용하십시오.

java'splatformincendenceenhancesmicroservicesarchitectureDeploymentFlexibility, 일관성, 확장 성 및 포트 가능성

Graalvm은 Java의 플랫폼 독립성을 세 가지 방식으로 향상시킵니다. 1. 교차 언어 상호 운용성, Java는 다른 언어와 원활하게 상호 작용할 수 있습니다. 2. 독립적 인 런타임 환경, Java 프로그램을 GraalvMnativeImage를 통해 로컬 실행 파일로 컴파일합니다. 3. 성능 최적화, Graal Compiler는 Java 프로그램의 성능과 일관성을 향상시키기 위해 효율적인 기계 코드를 생성합니다.

ToEffectIallyTestJavaApplicationSforplatformcompatibility, followthesesteps : 1) setupAutomatedTestingAcrossMultiplePlatflatformsUsingCitools likeJenkinsorgitHubactions.2) 행동 관리자는 realHardwaretoCathissesnotfoundInvironmentments.3) Checkcross-Pla

Java Compiler는 소스 코드를 플랫폼 독립적 인 바이트 코드로 변환하여 Java의 플랫폼 독립성을 실현하여 JVM이 설치된 JVM 프로그램에서 모든 운영 체제에서 실행할 수 있습니다.

Bytecodeachievesplatformincendence는 executedbirtualmachine (vm)을 beenecutedbyavirtmachine (vm)을 허용합니다

Java는 100% 플랫폼 독립성을 달성 할 수 없지만 플랫폼 독립성은 JVM 및 바이트 코드를 통해 구현되어 코드가 다른 플랫폼에서 실행되도록합니다. 특정 구현에는 다음이 포함됩니다. 1. 바이트 코드로의 컴파일; 2. JVM의 해석 및 실행; 3. 표준 라이브러리의 일관성. 그러나 JVM 구현 차이, 운영 체제 및 하드웨어 차이, 타사 라이브러리의 호환성은 플랫폼 독립성에 영향을 줄 수 있습니다.

Java는 "Writ 2. 유지 보수 비용이 낮 으면 하나의 수정 만 필요합니다. 3. 높은 팀 협업 효율성은 높고 지식 공유에 편리합니다.


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

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

드림위버 CS6
시각적 웹 개발 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기
