본문 바로가기

언어/Java

입출력 스트림 예시

 

public class FileIOTest {
	public static void write() {
		/*
		 * 스트림종류 : 바이트출력스트림
		 * 목적지 : 파일
		 */	
		String fileName = "D:\\b.txt";
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(fileName);
//			fos.write(65);
			byte[] bytes = "ABCDEFG".getBytes();
			fos.write(bytes);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    
	public static void main(String[] args) {
		write();		
	}

결과

FileOutputStream fos = new FileOutputStream("b.txt");

fos.write(65);

public class FileIOTest {
	public static void read() {
 		String fileName = "D:\\a.txt";	// \n \t가 아니라 원 표시는 \\ 2개
		/*
		 * 스트림종류 : 바이트입력스트림
		 * 자원 : 파일
		 */		
		
		FileInputStream fis;
		try {
			fis = new FileInputStream(fileName);
			int readValue = -1;
			while((readValue = fis.read()) != -1) {
				System.out.print((char)readValue);
			}
		} catch (FileNotFoundException e) {	// 자식 Exception부터 위에
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
			
	public static void main(String[] args) {
		read();	
	}
}

결과

※ a.txt 19바이트인 이유
abc 각 1바이트 3
123 각 1바이트 3
가나다 각 3바이트 9
1310 엔터 2바이트 4

 

public class FileIOTest {
	public static void write() {
		/*
		 * 스트림종류 : 문자출력스트림
		 * 목적지 : 파일
		 */
/*
		String fileName = "D:\\c.txt";
		FileWriter fw = null;
		try {
			fw = new FileWriter(fileName);
			fw.write("가나다라마바사");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	*/
		
		String fileName = "D:\\c.txt";
		FileWriter fw = null;
		try {
			fw = new FileWriter(fileName, true);	// 기존 파일이 있을 때 write할 내용 append함. 없을때만 새로 생성
			fw.write("가나다라마바사");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		write();
	}
}

결과

※ FileWriter fw = new FileWriter("c.txt");

fw.write("ABC"); 이 "ABC"는 내부버퍼에 새겨짐 그래서 fw.flush();로 목적지에 넣어줘야함
매번 fw.flush(); 할 수 없으니 fw.close();를 마지막에 해줌. flush+연결해제의 역할

public class FileIOTest {
	public static void read() {
 		String fileName = "D:\\a.txt";	// \n \t가 아니라 원 표시는 \\ 2개
		/*
		 * 스트림종류 : 문자입력스트림 FileReader
		 * 자원 : 파일
		 */
		
		FileReader fr = null;
		try {
			fr = new FileReader(fileName);	// 자원과의 연결
			int readValue = -1;
			while((readValue = fr.read()) != -1) {
				System.out.print((char)readValue);
			}	
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(fr != null) {
				try {
					fr.close(); // 자원과의 연결 끊어줘야함, open메서드는 없고 close 메서드는 있음
				//정상처리된 후에도, 예외가 발생해도 마지막에는 close 해줘야함
                } catch (IOException e) {
					e.printStackTrace();
				} 
			}
		}	
	}

	public static void main(String[] args) {
		read();
	}
}

결과

write('가'); = write(44032); // 한글 가 나옴

'언어 > Java' 카테고리의 다른 글

메타클래스, File 정보 가져오기  (0) 2023.08.09
FileCopy 예제  (0) 2023.08.09
프린트 스트림, System.in 예시  (0) 2023.08.09
입출력 스트림(Stream)  (0) 2023.08.09
어노테이션(Annotation)  (0) 2023.08.08