본문 바로가기

JAVA

기본적인 File I/O에 대한 이해

package 입출력;

import java.io.File;

public class Test {

	public static void main(String[] args) {
		
		// data.txt를 생성해야한다
		File file = new File("data.txt");
		// 파일의 절대적 경로를 알 수 있음, 절대적 경로란 document 주소임
		// 나는 C:\DEV\eclipse-workspace\study\hello\data
		System.out.println("파일 경로 : " + file.getAbsolutePath());
		
		// 존재하는가에 대해 boolean값을 돌려준다 있으면 true
		System.out.println("파일 존재 여부 : " + file.exists());
		
	}

}

 

*

절대경로(Absolute Path) : 루트 디렉토리로부터 시작하는 전체 경로

상대경로(Relative Path) : 현재 작업중인 디렉토리 기준으로 표시함

 

FileInputStream

package 입출력;

import java.io.FileInputStream;

public class Test {

	public static void main(String[] args) {
		
		// FileInputStream은 try-catch(finally)문이 필수이다
		try {
			// 기반 스트림 생성
			FileInputStream fileInput = new FileInputStream("data.txt");
			int i;
			// i에 넣은 read()는 입력스트림으로부터 1byte를 읽어서 반환한다. -1이 될때까지 계속 출력한다
			while((i = fileInput.read()) != -1) {
				System.out.print((char)i);
			}
			
			//스트림을 열었으면 반드시 닫아줘야한다. 메모리 누수가 발생하거나 예외가 발생함
			fileInput.close();
			
		}catch(Exception e) {
			System.out.println(e);
		}
		
	}

}

 

 

FileOutputStream (공부가 더 필요함)

https://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html

package 입출력;

import java.io.FileOutputStream;

public class Test {

	public static void main(String[] args) {
		
		// FileOutputStream도 마찬가지로 try-catch(finally)가 필수이다
		try {
			FileOutputStream fileOutput = new FileOutputStream("data.txt");
			String word = "ja";
			
			// getByte? 
			byte[] b = word.getBytes();
			//write()로 출력하고
			fileOutput.write(b);
			// 닫기
			fileOutput.close();
			
		}catch(Exception e) {
			System.out.println(e);
		}
		
	}

}

 

'JAVA' 카테고리의 다른 글

ByteArrayInputstream, ByteArrayOutputStream 예제  (0) 2025.06.15
문자 기반 스트림 : Reader, Writer  (1) 2025.06.14
I/O - 보조 스트림  (0) 2025.06.13
입출력 I/O - 바이트 기반 스트림  (1) 2025.06.13
객체 직렬화 / 역직렬화  (1) 2025.06.10