JAVA 기초

JAVA 19-1

Vanillwa 2023. 9. 6. 20:35

FileOutputStream

 

package ex3_fileOutput;

import java.io.FileOutputStream;

public class Ex1_fileOutputStream {
	public static void main(String[] args) {
		// 바이트 기반의 출력 스트림의 최상위 객체인 OutputStream 객체
		// 해당 객체를 상속하는 다양한 출력 스트림들이 존재
		try {
			FileOutputStream fos = new FileOutputStream("D:\\WEB15_YJH/FileOut.txt", true);
			fos.write('f'); // write() : 파일에 1바이트씩 출력
			fos.write('i');
			fos.write('l');
			fos.write('e');

			String msg = "\nfileOutput 예제입니다.\n";
			String msg2 = "여러줄도 가능\n";

			fos.write(msg.getBytes());
			fos.write(msg2.getBytes());

			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

실행 결과

 


 

FileReader

 

package ex4_fileReader;

import java.io.FileReader;

public class Ex1_fileReader {
	public static void main(String[] args) {
		// char 기반의 스트림은 reader writer의 자식 클래스들을 사용
		// 기본적으로 2byte를 지원하기에 2byte언어로 구성된 파일을 쉽게 입출력 가능
		
		try {
			FileReader fr = new FileReader("C:\\WEB\\work\\Ex_0905/test.txt");
			int code = 0;
			
			while((code = fr.read()) != -1) {
				System.out.print((char)code);
			}
			fr.close();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

test.txt 내용
실행 결과

 


 

FileReader로 파일 읽어와 대소문자 구별하기

 

package ex4_fileReader;

import java.io.File;
import java.io.FileReader;

public class Ex2_fileReader {
	public static void main(String[] args) {
		// test.txt 파일의 내용을 읽어와서 알파벳 대문자와 소문자의 개수 카운트하기
		File f = new File("C:\\WEB\\work\\Ex_0905/test.txt");
		int upper = 0, lower = 0;
		
		try {
			FileReader fr = new FileReader(f);
			int code = 0;

			while ((code = fr.read()) != -1) {
				if (Character.isUpperCase((char)code)) {
					upper++;
				}
				else if (Character.isLowerCase((char)code)) {
					lower++;
				}
			}
			System.out.printf("대문자 : %d개\n소문자 : %d개\n", upper, lower);
			
			fr.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

실행 결과

 


 

FileWriter

 

package ex5_fileWriter;

import java.io.File;
import java.io.FileWriter;

public class Ex1_fileWriter {
	public static void main(String[] args) {
		File f = new File("C:\\WEB\\work\\Ex_0905/fileWriter.txt");
		
		try {
			FileWriter fw = new FileWriter(f,true);
			
			fw.write("첫번째 문자열\n");
			fw.write("두번째 문자열\n");
			
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

실행 결과

 


 

'JAVA 기초' 카테고리의 다른 글

JAVA 20-1  (0) 2023.09.07
JAVA 19-2  (0) 2023.09.06
JAVA 18-1  (0) 2023.09.05
JAVA 17-2  (0) 2023.09.05
JAVA 17-1  (0) 2023.09.05