[자바 소스] Stream단위 파일 입출력 예제 :: 소림사의 홍반장!
import java.io.*;

class Ex114_InputOutput
{
	public static void main(String[] args) throws IOException
	{
		//Ex114_InputOutput.java

		// 파일 입출력
		//1. 바이트 단위
		//	- FileInputStream
		//	- FileOutputStream
		//2. 문자 단위
		//	- FileReader
		//	- FileWriter
		//	- 바이트 단위 입출력 클래스를 Wrapping한 클래스
		
		//m1();		//파일로 출력
		//m2();		//파일에서 읽기
		m3();		//파일 이어쓰기 출력

	}//end main;

	public static void m1()
	{
		//모든 입력은 예외처리 필수!!
		try
		{
			//사용자 출력
			//파일 쓰기
			
			//출력전용스트림(빨대)
			//기본 : 덮어쓰기(Create mode)

			//Create mode
			//	- 파일이 없으면 생성 후 기록
			//	- 파일이 있으면 덮어쓰기

			FileOutputStream stream = 
				new FileOutputStream("D:\\data.txt");
			
			//a~d
			stream.write(97);
			stream.write(98);
			stream.write(99);
			stream.write(100);

			stream.close();	//스트림 닫기

			System.out.println("기록 완료");


		}
		catch(Exception e) {
			System.out.println("오류");
		}

	}//end m1();

	public static void m2()
	{
		//모든 입력은 예외처리 필수!!
		try
		{
			//파일 읽기
			FileInputStream stream =
				new FileInputStream("D:\\data.txt");

			int code = 0;
			
			while((code = stream.read()) != -1)
			{
				System.out.println((char)code);
			}

			stream.close();
			System.out.println("읽기 완료");
		} catch(Exception e) {
			System.out.println("오류");
		}

	}//end m2();

	//파일 쓰기 - append mode
	public static void m3() {
		try
		{
			//Append mode
			//	- 파일이 존재하면 이어쓰기
			//	- 파일이 없으면 생성 -> 이어쓰기
			FileOutputStream stream = 
				new FileOutputStream("D:\\data.txt", true);

			stream.write(65);
			stream.write(66);
			stream.write(67);

			stream.close();

		}catch(Exception e) {
			System.out.println("오류");
		}//end try~catch

	}//end m3()


}

다른 카테고리의 글 목록

Dev. 자바/참고소스 카테고리의 포스트를 톺아봅니다