산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> java

자바 파일 클래스

자바 파일 클래스

이 자습서에서는 예제를 통해 Java 파일과 다양한 작업에 대해 배웁니다.

File java.io 클래스 패키지는 파일 및 디렉토리에 대한 다양한 작업을 수행하는 데 사용됩니다.

java.nio이라는 다른 패키지가 있습니다. 파일 작업에 사용할 수 있습니다. 그러나 이 튜토리얼에서는 java.io 패키지.

<시간>

파일 및 디렉토리

파일은 관련 정보를 저장하는 데 사용할 수 있는 명명된 위치입니다. 예를 들어,

메인.자바 Java 프로그램에 대한 정보가 포함된 Java 파일입니다.

디렉토리는 파일과 하위 디렉토리의 모음입니다. 디렉토리 안의 디렉토리를 하위 디렉토리라고 합니다.

<시간>

자바 파일 개체 만들기

File 개체를 생성하려면 , java.io.File를 가져와야 합니다. 먼저 패키지. 패키지를 가져온 후 파일 개체를 만드는 방법은 다음과 같습니다.

// creates an object of File using the path 
File file = new File(String pathName);

여기에서 file이라는 파일 개체를 만들었습니다. . 개체는 파일 및 디렉터리 작업에 사용할 수 있습니다.

참고 :Java에서 파일 객체를 생성한다고 해서 파일이 생성되는 것은 아닙니다. 대신 파일 개체는 파일 또는 디렉터리 경로 이름(괄호 안에 지정)의 추상 표현입니다.

<시간>

자바 파일 작업 방법

작업 방법 패키지
파일을 생성하려면 createNewFile() java.io.File
파일 읽기 read() java.io.FileReader
파일 쓰기 write() java.io.FileWriter
파일 삭제 delete() java.io.File
<시간>

자바 생성 파일

새 파일을 만들려면 createNewFile()을 사용할 수 있습니다. 방법. 그것은 반환

예:새 파일 만들기

// importing the File class
import java.io.File;

class Main {
  public static void main(String[] args) {

    // create a file object for the current location
    File file = new File("newFile.txt");

    try {

      // trying to create a file based on the object
      boolean value = file.createNewFile();
      if (value) {
        System.out.println("The new file is created.");
      }
      else {
        System.out.println("The file already exists.");
      }
    }
    catch(Exception e) {
      e.getStackTrace();
    }
  }
}

위의 예에서 file이라는 파일 객체를 생성했습니다. . 파일 개체는 지정된 파일 경로와 연결됩니다.

File file = new File("newFile.txt");

여기에서는 파일 개체를 사용하여 지정된 경로로 새 파일을 생성했습니다.

newFile.txt가 현재 위치에 없는 경우 , 파일이 생성되고 이 메시지가 표시됩니다.

The new file is created.

그러나 newFile.txt가 이미 있는 경우 , 이 메시지가 표시됩니다.

The file already exists.
<시간>

자바 읽기 파일

파일에서 데이터를 읽으려면 InputStream 또는 Reader의 하위 클래스를 사용할 수 있습니다.

예:FileReader를 사용하여 파일 읽기

input.txt라는 파일이 있다고 가정합니다. 다음 내용으로.

This is a line of text inside the file. 

이제 Java FileReader를 사용하여 파일을 읽어 보겠습니다. .

// importing the FileReader class
import java.io.FileReader;

class Main {
  public static void main(String[] args) {

    char[] array = new char[100];
    try {
      // Creates a reader using the FileReader
      FileReader input = new FileReader("input.txt");

      // Reads characters
      input.read(array);
      System.out.println("Data in the file:");
      System.out.println(array);

      // Closes the reader
      input.close();
    }
    catch(Exception e) {
      e.getStackTrace();
    }
  }
}

출력

Data in the file:
This is a line of text inside the file.

위의 예에서 우리는 입력이라는 이름의 FileReader 객체를 생성했습니다. 이제 input.txt와 연결됩니다. 파일.

FileReader input = new FileReader("input.txt");

input.txt에서 데이터를 읽으려면 파일에서 FileReader의 read() 메서드를 사용했습니다. .

<시간>

Java 파일에 쓰기

파일에 데이터를 쓰기 위해 OutputStream 또는 Writer의 하위 클래스를 사용할 수 있습니다.

예:FileWriter를 사용하여 파일에 쓰기

// importing the FileWriter class
import java.io.FileWriter;

 class Main {
   public static void main(String args[]) {

     String data = "This is the data in the output file";
     try {
       // Creates a Writer using FileWriter
       FileWriter output = new FileWriter("output.txt");

       // Writes string to the file
       output.write(data);
       System.out.println("Data is written to the file.");

       // Closes the writer
       output.close();
     }
     catch (Exception e) {
       e.getStackTrace();
     }
  }
}

출력

Data is written to the file.

위의 예에서는 FileWriter을 사용하여 작성기를 만들었습니다. 수업. 작성자는 output.txt와 연결됩니다. 파일.

FileWriter output = new FileWriter("output.txt");

파일에 데이터를 쓰기 위해 write()을 사용했습니다. 메소드.

여기에서 프로그램을 실행할 때 output.txt 파일은 다음 내용으로 채워집니다.

This is the data in the output file.
<시간>

자바 삭제 파일

delete()을 사용할 수 있습니다. 파일 메소드 지정된 파일이나 디렉토리를 삭제하는 클래스입니다. 그것은 반환

참고 :빈 디렉토리만 삭제할 수 있습니다.

예:파일 삭제

import java.io.File;

class Main {
  public static void main(String[] args) {

    // creates a file object
    File file = new File("file.txt");

    // deletes the file
    boolean value = file.delete();
    if(value) {
      System.out.println("The File is deleted.");
    }
    else {
      System.out.println("The File is not deleted.");
    }
  }
}

출력

The File is deleted.

위의 예에서 우리는 file이라는 이름의 File 객체를 생성했습니다. 이제 파일은 지정된 파일에 대한 정보를 보유합니다.

File file = new File("file.txt");

여기에서는 delete()을 사용했습니다. 객체가 지정한 파일을 삭제하는 메소드입니다.


java

  1. 자바 최종 키워드
  2. 자바 instanceof 연산자
  3. 자바 상속
  4. 자바 중첩 정적 클래스
  5. 자바 익명 클래스
  6. 자바 싱글톤 클래스
  7. 자바 리플렉션
  8. 자바 ObjectOutputStream 클래스
  9. 자바 BufferedReader 클래스
  10. 자바 제네릭