관리 메뉴

거니의 velog

230906_입출력 2 본문

대덕인재개발원_자바기반 애플리케이션

230906_입출력 2

Unlimited00 2023. 9. 6. 09:04

[FileIOTest05.java]

package kr.or.ddit.basic;

import java.io.FileReader;
import java.io.IOException;

public class FileIOTest05 {

	public static void main(String[] args) {
		
		/*
		 * 한글이 저장된 파일 읽어오기
		 * (한글의 인코딩 방식을 지정해서 읽어오기)
		 */
		
		try {
			FileReader fr = new FileReader("d:/d_other/test_ansi.txt");
			
			int c;
			while( (c = fr.read()) != -1 ) {
				System.out.print( (char)c );
			}
			
			fr.close();
		} catch (IOException e) {
			// TODO: handle exception
		}
		
	}

}

package kr.or.ddit.basic;

import java.io.FileReader;
import java.io.IOException;

public class FileIOTest05 {

	public static void main(String[] args) {
		
		/*
		 * 한글이 저장된 파일 읽어오기
		 * (한글의 인코딩 방식을 지정해서 읽어오기)
		 */
		
		try {
//			FileReader fr = new FileReader("d:/d_other/test_ansi.txt");
			FileReader fr = new FileReader("d:/d_other/test_utf8.txt");
			
			int c;
			while( (c = fr.read()) != -1 ) {
				System.out.print( (char)c );
			}
			
			fr.close();
		} catch (IOException e) {
			// TODO: handle exception
		}
		
	}

}

package kr.or.ddit.basic;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileIOTest05 {

	public static void main(String[] args) {
		
		/*
		 * 한글이 저장된 파일 읽어오기
		 * (한글의 인코딩 방식을 지정해서 읽어오기)
		 */
		
		try {
//			FileReader fr = new FileReader("d:/d_other/test_ansi.txt");
//			FileReader fr = new FileReader("d:/d_other/test_utf8.txt");
			
			FileInputStream fin = new FileInputStream("d:/d_other/test_ansi.txt");
//			FileInputStream fin = new FileInputStream("d:/d_other/test_utf8.txt");
			
			// 기본 인코딩 방식으로 읽어온다.
//			InputStreamReader isr = new InputStreamReader(fin);
			
			// 인코딩 방식을 지정해서 읽어오기
			// 인코딩 방식 예시
			// - MS949 ==> 윈도우의 기본 한글 인코딩 방식(ANSI방식)
			// - UTF-8 ==> 유니코드 UTF-8 인코딩 방식
			// - US-ASCII ==> 영문 전용 인코딩 방식
			
			InputStreamReader isr = new InputStreamReader(fin, "ms949");
//			InputStreamReader isr = new InputStreamReader(fin, "utf-8");
			
			int c;
			
//			while( (c = fr.read()) != -1 ) {
			
			while( (c = isr.read()) != -1 ) {
				System.out.print( (char)c );
			}
			
			isr.close();
			
		} catch (IOException e) {
			// TODO: handle exception
		}
		
	}

}



[BufferIOTest01.java]

package kr.or.ddit.basic;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferIOTest01 {

	public static void main(String[] args) {
		
		// 입출력의 성능 향상을 위해서 Buffered 스트림을 사용한다.
		try {
			FileOutputStream fout = new FileOutputStream("d:/d_other/bufferTest.txt");
			
			BufferedOutputStream bout = new BufferedOutputStream(fout, 5);
			
			for(int i='1'; i<='9'; i++) {
				bout.write(i);
			}
			
			System.out.println("작업 끝...");
			
		} catch (IOException e) {
			// TODO: handle exception
		}
		
	}

}

package kr.or.ddit.basic;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferIOTest01 {

	public static void main(String[] args) {
		
		// 입출력의 성능 향상을 위해서 Buffered 스트림을 사용한다.
		try {
			FileOutputStream fout = new FileOutputStream("d:/d_other/bufferTest.txt");
			
			BufferedOutputStream bout = new BufferedOutputStream(fout, 5);
			
			for(int i='1'; i<='9'; i++) {
				bout.write(i);
			}
			
//			bout.flush(); // 출력 버퍼에 남아 있는 데이터를 강제로 모두 출력 시킨다.
			
			bout.close(); // 보조 스트림을 닫으면 보조 스트림에서 사용한 기반 스트림도 같이 닫힌다.
						  // Buffered 스트림의 close() 메서드에는 flush() 기능이 내장되어 있다.
			
			System.out.println("작업 끝...");
			
		} catch (IOException e) {
			// TODO: handle exception
		}
		
	}

}


[BufferIOTest02.java]

package kr.or.ddit.basic;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferIOTest02 {

	public static void main(String[] args) {
		
		// 문자 기반의 Buffered 스트림 사용 예제
		try {
//			FileReader fr = new FileReader("D:/A_TeachingMaterial/03_HighJava/workspace/javaIOTest/src/kr/or/ddit/basic/FileTest01.java");
			// 이클립스에서 자바 프로그램이 실행되는 현재 위치는
			// 해당 프로젝트 폴더가 현재 위치가 된다.
			FileReader fr = new FileReader("./src/kr/or/ddit/basic/FileTest01.java");
			BufferedReader br = new BufferedReader(fr);
			
			// 문자 기반의 Buffered 스트림에는 줄 단위로 입출력하는 기능이 있다.
			String temp = "";
			
			for(int i=1; (temp = br.readLine()) != null; i++) {
				System.out.printf("%4d : %s\n", i, temp);
			}
			
			br.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}


[FileCopyTest.java]

package kr.or.ddit.basic;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 문제)
 * 		'd:/d_other'폴더에 있는 '펭귄.jpg'파일을
 * 		'd:/d_other/연습용'폴더에 '펭귄_복사본.jpg'파일로 
 * 		복사하는 프로그램을 작성하시오.
 */
public class FileCopyTest {

	public static void main(String[] args) {
		
		try {
			// 원본 파일 읽어들이기
			File file = new File("d:/d_other/펭귄.jpg");
			FileInputStream fin = new FileInputStream(file);
			BufferedInputStream bin = new BufferedInputStream(fin);
			
			// 복사할 위치 선정하기
			FileOutputStream fout = new FileOutputStream("d:/d_other/연습용/펭귄_복사본.jpg");
			BufferedOutputStream bout = new BufferedOutputStream(fout);
			
			// 버퍼 스트림으로 작업
			int data;
			while( (data = bin.read()) != -1 ) {
				bout.write(data);
			}
			
			bout.flush();
			
			bin.close();
			bout.close();
			System.out.println("복사 완료...");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}

package kr.or.ddit.basic;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 문제)
 * 		'd:/d_other'폴더에 있는 '펭귄.jpg'파일을
 * 		'd:/d_other/연습용'폴더에 '펭귄_복사본.jpg'파일로 
 * 		복사하는 프로그램을 작성하시오.
 */
public class FileCopyTest {

	public static void main(String[] args) {
		
		// 원본 파일 읽어들이기
		File file = new File("d:/d_other/펭귄.jpg");
		
		if(!file.exists()) {
			System.out.println(file.getName() + " 파일이 없습니다...");
			System.out.println("복사 작업을 중단합니다...");
			return;
		}
		
		try {
			// 입력용 스트림과 출력용 스트림 객체 생성
			FileInputStream fin = new FileInputStream(file);
			FileOutputStream fout = new FileOutputStream("d:/d_other/연습용/펭귄_복사본.jpg");
			
			// 입력용 버퍼 스트림과 출력용 버퍼 스트림 객체 생성
			BufferedInputStream bin = new BufferedInputStream(fin);
			BufferedOutputStream bout = new BufferedOutputStream(fout);
			
			System.out.println("복사 시작...");
			
			// 스트림으로 작업
//			int data;
//			while( (data = fin.read()) != -1 ) {
//				fout.write(data);
//			}
			
//			fout.close();
//			fin.close();
			
			// 버퍼 스트림으로 작업
//			int data;
//			while( (data = bin.read()) != -1 ) {
//				bout.write(data);
//			}
			
			// 배열을 이용한 입출력 작업, 1024의 배수로 많이 사용함.
			byte[] temp = new byte[1024];
			int len = 0;
			while( (len = bin.read(temp)) != -1 ) {
				bout.write(temp, 0, len);
			}
			
			bout.flush();
			
			// 버퍼 닫기
			bin.close();
			bout.close();
			
			System.out.println("복사 작업 완료...");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}

[DialogTest.java]

package kr.or.ddit.basic;

import java.awt.Panel;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

public class DialogTest {

	public static void main(String[] args) {
		
		// AWT ==> SWING ==> javaFX
		
		// SWING의 파일 열기, 저장 창 연습
		JFileChooser chooser = new JFileChooser();
		
		// 선택할 파일의 종류 설정하기 (파일의 확장자를 이용하여 구별한다.)
		FileNameExtensionFilter txt = new FileNameExtensionFilter("Text파일(*.txt)", "txt");
		FileNameExtensionFilter img = new FileNameExtensionFilter("그림파일", "png", "jpg", "gif");
		FileNameExtensionFilter doc = new FileNameExtensionFilter("MS Word파일", new String[] {"doc", "docx"});
		
		chooser.addChoosableFileFilter(txt);
		chooser.addChoosableFileFilter(img);
		chooser.addChoosableFileFilter(doc);
		
		// '모든 파일'이라는 항목의 표시 여부 설정 (true: 설정, false: 해제)
		// (기본값 : true)
//		chooser.setAcceptAllFileFilterUsed(true);
//		chooser.setAcceptAllFileFilterUsed(false);
		
		// Dialog창에 나타날 기본 경로 설정 ('d:/d_other'로 설정하기)
		chooser.setCurrentDirectory(new File("d:/d_other"));
		
//		int result = chooser.showOpenDialog(new Panel()); // 열기용
		int result = chooser.showSaveDialog(new Panel()); // 저장용
		
		// 창에서 '저장' 또는 '열기' 버튼을 눌렀을 때를 검사한다.
		if(result == JFileChooser.APPROVE_OPTION) {
			File selectedFile = chooser.getSelectedFile();
			System.out.println("선택한 파일 : " + selectedFile.getAbsolutePath());
		}
		
	}

}

[FileCopyDialogTest.java]

package kr.or.ddit.basic;

import java.awt.Panel;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

/*
 * 문제)
 * 		'd:/d_other'폴더에 있는 '펭귄.jpg'파일을
 * 		'd:/d_other/연습용'폴더에 '펭귄_복사본.jpg'파일로 
 * 		복사하는 프로그램을 작성하시오.
 */
public class FileCopyDialogTest {

	public static void main(String[] args) {
		
		FileCopyDialogTest copy = new FileCopyDialogTest();
		
//		File file = new File("d:/d_other/펭귄.jpg");
		
		// 복사할 원본 파일 선택하기
		File file = copy.showDialog("open");
		
		if(file == null) {
			System.out.println("원본 파일을 선택하지 않았습니다.");
			System.out.println("복사 작업을 중단합니다...");
			return;
		}
		
		if(!file.exists()) {
			System.out.println(file.getName() + " 파일이 없습니다...");
			System.out.println("복사 작업을 중단합니다...");
			return;
		}
		
		try {
			// 입력용 스트림과 출력용 스트림 객체 생성
			FileInputStream fin = new FileInputStream(file);
			
			// 복사될 대상 파일 선택하기
			File targetFile = copy.showDialog("save");
			
			if(targetFile == null) {
				System.out.println("복사할 대상 파일을 선택하지 않았습니다.");
				System.out.println("복사 작업을 중단합니다...");
				return;
			}
			
//			FileOutputStream fout = new FileOutputStream("d:/d_other/연습용/펭귄_복사본.jpg");
			FileOutputStream fout = new FileOutputStream(targetFile);
			
			// 입력용 버퍼 스트림과 출력용 버퍼 스트림 객체 생성
			BufferedInputStream bin = new BufferedInputStream(fin);
			BufferedOutputStream bout = new BufferedOutputStream(fout);
			
			System.out.println("복사 시작...");
			
			// 스트림으로 작업
//			int data;
//			while( (data = fin.read()) != -1 ) {
//				fout.write(data);
//			}
			
//			fout.close();
//			fin.close();
			
			// 버퍼 스트림으로 작업
//			int data;
//			while( (data = bin.read()) != -1 ) {
//				bout.write(data);
//			}
			
			// 배열을 이용한 입출력 작업, 1024의 배수로 많이 사용함.
			byte[] temp = new byte[1024];
			int len = 0;
			while( (len = bin.read(temp)) != -1 ) {
				bout.write(temp, 0, len);
			}
			
			bout.flush();
			
			// 버퍼 닫기
			bin.close();
			bout.close();
			
			System.out.println("복사 작업 완료...");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	// Dialog창을 나타내고 선택한 파일을 반환하는 메서드
	// option이 'open'이면 열기창, 'save'면 저장창을 나타낸다.
	public File showDialog(String option) {
		
		// SWING의 파일 열기, 저장 창 연습
		JFileChooser chooser = new JFileChooser();
		
		// 선택할 파일의 종류 설정하기 (파일의 확장자를 이용하여 구별한다.)
		FileNameExtensionFilter txt = new FileNameExtensionFilter("Text파일(*.txt)", "txt");
		FileNameExtensionFilter img = new FileNameExtensionFilter("그림파일", "png", "jpg", "gif");
		FileNameExtensionFilter doc = new FileNameExtensionFilter("MS Word파일", new String[] {"doc", "docx"});
		
		chooser.addChoosableFileFilter(txt);
		chooser.addChoosableFileFilter(img);
		chooser.addChoosableFileFilter(doc);
		
		// '모든 파일'이라는 항목의 표시 여부 설정 (true: 설정, false: 해제)
		// (기본값 : true)
		chooser.setAcceptAllFileFilterUsed(true);
//		chooser.setAcceptAllFileFilterUsed(false);
		
		// Dialog창에 나타날 기본 경로 설정 ('d:/d_other'로 설정하기)
		chooser.setCurrentDirectory(new File("d:/d_other"));
		
		int result;
		
		if("save".equals(option.toLowerCase())) {
			result = chooser.showSaveDialog(new Panel()); // 저장용
		}else if("open".equals(option.toLowerCase())) {
			result = chooser.showOpenDialog(new Panel()); // 열기용
		}else {
			System.out.println("option변수에는 save 또는 open만 가능합니다.");
			return null;
		}
		
		File selectedFile = null;
		
		// 창에서 '저장' 또는 '열기' 버튼을 눌렀을 때를 검사한다.
		if(result == JFileChooser.APPROVE_OPTION) {
			selectedFile = chooser.getSelectedFile();
		}
		
		return selectedFile;
		
	}

}


 

'대덕인재개발원_자바기반 애플리케이션' 카테고리의 다른 글

230908_입출력 4  (0) 2023.09.08
230907_입출력 3  (2) 2023.09.07
230905_입출력 1  (0) 2023.09.04
230904_스레드 5  (0) 2023.09.04
230901_스레드 4  (0) 2023.09.01