> Java > java지도 시간 > 본문

Java의 텍스트 파일

WBOY
풀어 주다: 2024-08-30 15:54:18
원래의
1008명이 탐색했습니다.

프로그래머는 파일 읽기 및 쓰기가 필요한 Java 애플리케이션으로 작업하는 동안 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가지 모의고사

Java의 텍스트 파일

방법 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);
    }
}
로그인 후 복사

출력:

Java의 텍스트 파일

방법 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);
    }
}
로그인 후 복사

출력:

Java의 텍스트 파일

방법 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());
  }
}
로그인 후 복사

출력:

Java의 텍스트 파일

방법 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) {
		}
	}

}
로그인 후 복사

출력:

Java의 텍스트 파일

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:

Java의 텍스트 파일

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:

Java의 텍스트 파일

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:

Java의 텍스트 파일

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:

Java의 텍스트 파일

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

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!