Building value

Java[파일&폴더(File&Folder)] 본문

Java

Java[파일&폴더(File&Folder)]

developer_Michael 2023. 3. 29. 19:09
반응형

자바에서 파일 및 폴더를 다루는 방법은 java.io 패키지에서 제공하는 클래스와 메소드를 사용하는 것입니다. 

 

이 패키지는 파일과 폴더를 조작하고 데이터를 읽고 쓰기 위한 다양한 클래스를 제공합니다.

// 파일 생성
import java.io.File;
import java.io.IOException;

public class CreateFileExample {
    public static void main(String[] args) {
        File file = new File("example.txt");

        try {
            boolean result = file.createNewFile();
            if (result) {
                System.out.println("File created successfully");
            } else {
                System.out.println("File already exists");
            }
        } catch (IOException e) {
            System.out.println("An error occurred while creating the file: " + e.getMessage());
        }
    }
}
// 파일 쓰기

import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("example.txt");
            writer.write("Hello, world!");
            writer.close();
            System.out.println("Data written successfully");
        } catch (IOException e) {
            System.out.println("An error occurred while writing to the file: " + e.getMessage());
        }
    }
}
// 파일 읽기

import java.io.FileReader;
import java.io.IOException;

public class ReadFromFileExample {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("example.txt");
            int data = reader.read();
            while (data != -1) {
                System.out.print((char) data);
                data = reader.read();
            }
            reader.close();
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        }
    }
}
// 파일 삭제

import java.io.File;

public class DeleteFileExample {
    public static void main(String[] args) {
        File file = new File("example.txt");

        if (file.delete()) {
            System.out.println("File deleted successfully");
        } else {
            System.out.println("Failed to delete the file");
        }
    }
}
// 폴더 생성

import java.io.File;

public class CreateFolderExample {
    public static void main(String[] args) {
        File folder = new File("example");

        boolean result = folder.mkdir();
반응형

'Java' 카테고리의 다른 글

Java[스트림(Stream)]  (0) 2023.03.29
Java[스레드(Thread)]  (0) 2023.03.29
Java[람다식(Lambda)]  (0) 2023.03.29
Java[Iterator]  (0) 2023.03.29
Java[HashMap]  (0) 2023.03.29