본문 바로가기
IT/Java

파일읽기 쓰기 (FileInputStream, FileOutputStream)

by 성준하이 2023. 9. 16.
반응형

자바에서 파일을 읽기위해서는 FileInputStream

파일을 쓰기 위해서는 FileOutputStream 를 사용하곤 한다.

(다른것들도 있음)

 

이 두 클래스 이전에 파일 클래스를 알아야한다.

File클래스란
import java.io.File 위치에 있다.
파일은 기본적이면서도 가장 많이 사용되는 입출력 대상이기 때문에 중요하다.
자바에서는 File클래스를 통해서 파일과 디렉토리를 다룰 수 있도록 하고있다. 그래서 File인스턴스는 파일일 수도 있고 디렉토리일 수도 있다.

 

그리고 오늘 알아볼 클래스 역시 File과 동일한 위치에 있다.

import java.io.FileInputStream;

import java.io.FileOutputStream;

 

기본 사용법은 다음과 같다.

파일 생성 및 쓰기
public static void main(String[] args) {
        
        File file = new File("c:\\file.txt");

        try {
            if (file.createNewFile()) {
                System.out.println("File created");
            } else {
                System.out.println("File already exists");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
public static void main(String[] args) {

        File file = new File("c:\\file.txt");

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file, true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
    }

 

파일 읽기
File file = new File("src/file/file.txt");
FileInputStream fis1 = new FileInputStream(file);

FileInputStream fis2 = new FileInputStream("src/file/nextFile.java");

 

반응형

댓글