>  기사  >  Java  >  Java의 파일 처리

Java의 파일 처리

WBOY
WBOY원래의
2024-08-30 15:36:53891검색

파일 처리란 Java에서 파일을 작업하는 것을 말합니다. 파일을 읽고 Java 파일에 쓰는 것을 Java의 파일 처리라고 합니다. 파일은 다양한 유형의 정보를 담을 수 있는 컨테이너입니다. 파일에는 텍스트, 이미지, 비디오, 표 등이 포함될 수 있습니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java에서 File 클래스를 사용하면 다양한 유형의 파일로 작업할 수 있습니다. File 클래스는 java.io 패키지의 멤버입니다. Java는 파일을 읽고, 쓰고, 업데이트하고, 삭제할 수 있는 다양한 방법을 제공합니다.

운영유형

파일에 대해 수행할 수 있는 다양한 작업 유형은 다음과 같습니다.

Java의 파일 처리

  • 파일 생성
  • 파일 업데이트
  • 파일 삭제
  • 특정 위치에 파일 업로드
  • 파일 열기
  • 파일을 닫는 중

구문:

프로그램에서 파일 작업을 하려면 java.io 패키지를 가져와야 합니다. 이 패키지를 가져오면 File 클래스의 생성자에서 파일을 참조하여 초기화할 수 있는 File 클래스가 제공됩니다.

//importing file class
import java.io.File;
//File name passed to the object
File fileObj = new File("file.txt");

파일 처리는 어떻게 진행되나요?

Java에서는 스트리밍 개념으로 파일 처리가 이루어집니다. 파일에 대한 입출력 작업은 스트리밍을 통해 수행됩니다. 스트림은 일련의 데이터를 의미합니다.

Java에서 Stream은 두 가지 유형이 있습니다.

Java의 파일 처리

  • 캐릭터 스트림: 캐릭터 스트림은 캐릭터와 관련된 스트림을 말합니다. 데이터 처리는 파일의 문자 스트림을 통해 이루어집니다.
  • 바이트 스트림: 데이터를 바이트 단위로 전송하는 스트림을 바이트 스트림이라고 부릅니다. 데이터 처리는 파일의 바이트 스트림을 통해 이루어집니다.

파일 처리 방법

Java에서 다양한 작업을 수행하기 위한 몇 가지 방법이 아래에 나와 있습니다.

  1. createNewFile(): createNewFile 메소드는 빈 파일을 만드는 데 사용됩니다. 응답을 부울로 반환합니다.
  2. getName(): 이 메소드는 파일 이름을 가져오는 데 사용됩니다. 문자열, 즉 응답으로 파일 이름을 반환합니다.
  3. getAbsolutePath(): 파일의 절대 경로를 반환합니다. 이 메소드의 반환 유형은 문자열입니다.
  4. canRead(): 이 메소드는 파일을 읽을 수 있는지 여부를 확인합니다. 부울 값을 반환합니다.
  5. canWrite(): 이 메소드는 파일이 쓰기 가능한지 여부를 확인합니다. 부울 값을 반환합니다.
  6. delete(): 이 메서드는 파일을 삭제할 때 사용됩니다. 부울 값을 반환합니다.
  7. exists(): 파일이 존재하는지 확인하려면 이 방법을 사용하세요. 부울 값을 반환합니다.
  8. length(): 이 메서드는 파일 크기를 바이트 단위로 반환합니다. 이 메소드의 반환 유형은 길다.
  9. list(): 이 메서드는 디렉터리에서 사용 가능한 파일의 배열을 반환합니다. 문자열 값의 배열을 반환합니다.
  10. mkdir(): 새 디렉터리를 만들려면 이 방법을 사용하세요. 부울 값을 반환합니다.

Java의 파일 처리 예

다음은 Java의 파일 처리 예입니다.

예시 #1

이 예에서 프로그램은 다양한 방법을 사용하여 특정 세부정보를 얻습니다. 이 애플리케이션에서는 파일과 관련된 정보를 가져오기 위해 다음과 같은 다양한 방법이 사용됩니다.

  1. 파일의 절대 경로를 검색합니다.
  2. 파일 쓰기 가능 여부를 확인하는 중입니다.
  3. 파일을 읽을 수 있는지 확인 중입니다.
  4. 파일명을 검색하는 중입니다.
  5. 파일 크기를 검색하는 중입니다.
  6. 지정된 디렉터리 등에 존재하는 파일 목록 가져오기

코드:

IO 패키지의 다양한 클래스를 가져옵니다.

import java.io.File;
import java.io.IOException;
public class FileHandlingExample2 {
public static void main(String[] args) {
// Creating an object of a file
File fileObj = new File("D:/Programs/fileHandlingOperations.txt");
if (fileObj.exists()) {
//retrieving the path of the specified file
System.out.println("\nSpecified file path: " + fileObj.getAbsolutePath());
//checking whether the file is writable or not
System.out.println("\nIs the file Writable: " + fileObj.canWrite());
//checking whether the file is Readable or not
System.out.println("\nIs the file Readable " + fileObj.canRead());
//retrieving file name
System.out.println("\nFile name: " + fileObj.getName());
//retrieving file size
System.out.println("\nFile size (in bytes) " + fileObj.length());
File fileDirObj = new File("D:/Programs/");
String[] fileList = fileDirObj.list();
//displaying here the list of files available in the directory
for (int i = 0; i < fileList.length; i++) {
System.out.print("\n" + fileList[i]);
}
System.out.println("\n");
}
else {
System.out.println("Specified file does not exist.");
}
}
}

출력:

위의 예에서는 파일과 관련된 다양한 검사를 수행하는 데 필요한 정보를 제공하는 다양한 방법을 확인할 수 있습니다.

Java의 파일 처리

예시 #2

이 예는 다양한 작업 유형에 대해 프로그램에서 다양한 방법이 사용되는 방식을 보여줍니다. 파일이 존재하는지 확인하기 위해 프로그램에서 사용되는 presents() 메소드는 존재하지 않습니다. 그 후 if..else.. 조건이 적용됩니다.

In the If condition, it checks first whether the existing file is writable or not; if the existing file remains writable, then the code block under the if section uses the FileWriter class method to write content into the existing file.

Code:

Importing io package different classes.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileHandlingExample {
public static void main(String[] args) {
try {
File fileObj = new File("D:/Programs/fileHandlingOperations.txt");
if(fileObj.exists()){
System.out.println("File already exists.");
if(fileObj.canWrite()){
//creating object of FileWriter class to write things on file
FileWriter fwObj = new FileWriter("D:/Programs/fileHandlingOperations.txt");
// Writes this content into the specified file
fwObj.write("It is a basic example of writing in file!");
//closing the files once writing completed
fwObj.close();
System.out.println("\nContent has been written to the file.");
}else{
System.out.println("\nFile is not in writable mode.");
}
;
}else{
if (fileObj.createNewFile()) {
System.out.println("New File created: " + fileObj.getName());
}
}
}
catch (IOException ioError) {
System.out.println("An error occurred.");
ioError.printStackTrace();
}
}
}

Output:

In the above-given example, After compilation, running the program the first time will create a file with the specified name in the program.

Java의 파일 처리

Running the program a second time will write the content in the existing file.

Java의 파일 처리

Conclusion

The article above explains what a file is, how to perform operations on it, and how file handling works. It was also demonstrated in the above section about classes & methods that can be used to work with files in java.

위 내용은 Java의 파일 처리의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:자바의 addAll()다음 기사:자바의 addAll()