Presentation is loading. Please wait.

Presentation is loading. Please wait.

11주 예외처리 (Exception Handling) 파일 입출력 (File Input and Output)

Similar presentations


Presentation on theme: "11주 예외처리 (Exception Handling) 파일 입출력 (File Input and Output)"— Presentation transcript:

1 11주 예외처리 (Exception Handling) 파일 입출력 (File Input and Output)
자바프로그래밍 강원대학교

2 내 마음은 - 김동명 내 마음은 호수요, 그대 노 저어 오오. 나 는 그대의 흰 그림자를 안고, 옥같이 그대의 뱃전에 부서지리다. 내 마음은 촛불이요, 그대 저 문을 닫아 주오. 나는 그대의 비단 옷자락에 떨며, 고요히 최후의 한 방울도 남김없이 타오리다. 내 마음은 나그네요, 그대 피리를 불어 주오. 나는 달 아래 귀를 기울이며, 호젓이 나의 밤을 새이오리다. 내 마음은 낙엽이요, 잠깐 그대의 뜰에 머무르게 하오. 이 제 바람이 일면 나는 또 나그네같이, 외로이 그대를 떠나오리다. 자바프로그래밍 강원대학교

3 /* 1 */ 내 마음은 /* 2 */ 김동명 /* 3 */ /* 4 */ 내 마음은 호수요, /* 5 */ 그대 노 저어 오오. /* 6 */ /* 7 */ 나 는 그대의 흰 그림자를 안고, /* 8 */ 옥같이 그대의 뱃전에 부서지리다. /* 9 */ /* 10 */ 내 마음은 촛불이요, /* 11 */ 그대 저 문을 닫아 주오. /* 12 */ /* 13 */ 나는 그대의 비단 옷자락에 떨며, 고요히 /* 14 */ 최후의 한 방울도 남김없이 타오리다. /* 15 */ /* 16 */ 내 마음은 나그네요, /* 17 */ 그대 피리를 불어 주오. /* 18 */ /* 19 */ 나는 달 아래 귀를 기울이며, 호젓이 /* 20 */ 나의 밤을 새이오리다. /* 21 */ /* 22 */ 내 마음은 낙엽이요, /* 23 */ 잠깐 그대의 뜰에 머무르게 하오. /* 24 */ /* 25 */ 이 제 바람이 일면 나는 또 나그네같이, 외로이 /* 26 */ 그대를 떠나오리다. 자바프로그래밍 강원대학교

4 import java.io.PrintWriter; import java.util.Scanner;
import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class LineNumberer { public void addNumber() Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next(); 자바프로그래밍 강원대학교

5 File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); int lineNumber = 1; while (in.hasNextLine()) { String line = in.nextLine(); out.println("/* " + lineNumber + " */ " + line); lineNumber++; } in.close(); out.close(); 예외적 상황이 발생할 수 있고 그 경우 예외가 던져지는데 이를 처리해 주지 않음! 컴파일 안됨. 자바프로그래밍 강원대학교

6 예외 (exception) exception = exceptional event
프로그램을 정상적으로 실행할 수 없게 만드는, 프로그램 실행 중 일어나는 이벤트 자바프로그래밍 강원대학교

7 예외 던지기 (throwing exceptions)
public class Scanner { public Scanner(File source) if (source does not exist) throw new FileNotFoundException(); } else ... Scanner(inputFile) 구성자의 내부를 들여다 보면? 경우에 따라 Exception을 던짐! 자바프로그래밍 강원대학교

8 어떤 문장이 예외를 던지면 그 문장의 실행이 중단되고 예외처리기가 실행됨 (예외처리기로 점프!) 자바프로그래밍 강원대학교

9 메소드 실행 중 발생한 예외를 처리하는 방법 즉시 예외 처리
예외가 발생하는 부분을 try 블록으로 묶고 그 아래에 예외처리기(catch 블록)를 둠 예외 발생 보고 (예외 전파) 이 메소드를 호출하는 곳에서 예외를 처리하도록 위임 이렇게 하는 경우 메소드 헤더에 이를 선언해야 함 자바프로그래밍 강원대학교

10 즉시 예외 처리 예외가 발생하는 부분을 try 블록으로 묶고 그 아래에 예외처리기(catch 블록)를 둠 자바프로그래밍
강원대학교

11 Scanner in = new Scanner(inputFile);
try { Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); } catch (IOException e) System.out.println("Scanner 혹은 PrintWriter 구성 불가!"); e.printStackTrace(); System.exit(0); int lineNumber = 1; while (in.hasNextLine()) String line = in.nextLine(); out.println("/* " + lineNumber + " */ " + line); lineNumber++; 자바프로그래밍 강원대학교

12 예외 발생 보고 (예외 전파) 이 메소드를 호출하는 곳에서 예외를 처리하도록 위임
이렇게 하는 경우 메소드 헤더에 이를 선언해야 함 자바프로그래밍 강원대학교

13 public void addNumber() throws IOException {
Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next(); File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); int lineNumber = 1; while (in.hasNextLine()) String line = in.nextLine(); out.println("/* " + lineNumber + " */ " + line); lineNumber++; } addNumber를 호출하는 곳에서 예외를 잡아 처리해야 함 (혹은 재전파) 자바프로그래밍 강원대학교

14 여러가지 예외가 발생하는 경우 IOException과 FileNotFoundException가 발생하는 경우에는 IOException만 적어줄 수도 있음 public void read(String filename) throws IOException, ClassNotFoundException { ... } 자바프로그래밍 강원대학교

15 확인예외와 비확인예외 (Checked Exception and Unchecked Exception)
확인예외: 이 예외가 던져지는 경우에 이를 적절히 처리하도록 프로그램되어 있는지를 컴파일러가 확인 RuntimeException을 제외한 모든 Exception 프로그래머의 책임이 아닌 예외들 예: 사용자가 잘 못된 입력을 하는 경우 비확인예외: RuntimeException (과 그 서브클래스들) 프로그래머의 책임인 예외들 자바프로그래밍 강원대학교

16 확인예외와 비확인예외 (Checked Exception and Unchecked Exception)
확인예외: 이 예외가 던져지는 경우에 이를 적절히 처리하도록 프로그램되어 있는지를 컴파일러가 확인 메소드 내에 확인예외를 던질 가능성이 있는데 이를 적절히 처리하지 않으면 컴파일이 되지 않음 비확인예외: 예외처리를 해 주지 않아도 컴파일에 문제 없음 자바프로그래밍 강원대학교

17 확인예외 (짙은 색) 자바프로그래밍 강원대학교

18 비확인 예외 실행시간예외 (Runtime Exception) 애플리케이션 내부적인 요인에 의해 발생
프로그램의 논리적 오류나 api의 잘못된 사용 등에 의해 발생 예: 0으로 나누거나 null 레퍼런스를 사용하여 객체에 접근하는 경우 등 예외처리기를 두는 것보다는 버그를 잡는 것이 좋음 Scanner의 nextInt 등의 메소드는 예외적인 케이스 자바프로그래밍 강원대학교

19 예외처리문장 형식 try { 예외를 발생시킬 가능성이 있는 문장 } catch (IOException e) { 예외처리기
} catch (ClassNotFoundException e) { } finally { 마무리처리기 } 0개 이상의 catch 블럭이 올 수 있으며 추가적으로 finally 블럭이 한 개 올 수도 있다. 자바프로그래밍 강원대학교

20 try { String filename = . . .; FileReader reader = new FileReader(filename); //FileNotFound Scanner in = new Scanner(reader); String input = in.next(); // NoSuchElementException int value = Integer.parseInt(input); // NumberFormatException } catch (IOException exception) // FileNotFoundException { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); } 자바프로그래밍 강원대학교

21 finally 예외가 발생하면 현재 수행중인 메소드는 중단됨 위험요소: 꼭 수행해야 할 일을 하지 못하게 되는 수가 있음
Example: reader.close 메소드가 어떤 경우건 꼭 실행되도록 하기 위해 finally 절을 사용함 reader = new FileReader(filename); Scanner in = new Scanner(reader); readData(in); reader.close(); // 이 문장이 실행되지 않을 수 있음! 자바프로그래밍 강원대학교

22 finally 블록 FileReader reader = new FileReader(filename); try { Scanner in = new Scanner(reader); readData(in); } catch (IOException exception) { exception.printStackTrace(); } finally { reader.close(); // if an exception occurs, finally clause // is also executed before exception is // passed to its handler } 자바프로그래밍 강원대학교

23 finally 블록 finally 블록이 있는 경우에는 프로그램이 try 블록을 빠져나오자마자 (예외 발생 여부와 관계 없이) 실행됨 try 블록 내에서 예외가 발생하면 예외가 발생한 문장에서 실행을 중단하고 try 블록을 빠져 나옴 try 블록 내에서 예외가 발생하지 않으면 try 블록 내 문장을 모두 실행하고 try 블록을 빠져 나옴 try 블록 내에서 return이 되는 경우에도 실행됨 try 블록에서 사용한 자원을 반납하거나 뒷정리하는 데 사용 자바프로그래밍 강원대학교

24 사용자 정의 예외 사용 Exception이나 RuntimeException을 확장하여 나름대로의 예외를 설계할 수 있음
두개의 구성자를 작성 기본구성자 (default constructor) 예외 원인을 문자열 파라미터로 받아들이는 구성자 if (amount > balance) { throw new InsufficientFundsException( "withdrawal of " + amount + " exceeds balance of “ + balance); } 자바프로그래밍 강원대학교

25 사용자 정의 예외 사용 public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException(String message) { super(message); } } 자바프로그래밍 강원대학교

26 예외 전파 메소드가 예외를 던지면 시스템은 그 예외를 처리할 메소드를 역으로 추적함 call stack 자바프로그래밍
강원대학교

27 (해당 예외를 처리할 수 있는) 적절한 처리기를 발견하면 시스템은 예외객체를 처리기로 넘겨줌
시스템은 call stack을 차례로 뒤져 예외를 처리하는 코드블럭을 포함하고 있는 메소드를 찾음 (예외처리기, exception handler) (해당 예외를 처리할 수 있는) 적절한 처리기를 발견하면 시스템은 예외객체를 처리기로 넘겨줌 예외처리기가 예외를 잡는다고 함 (catch the exception) 적절한 예외처리기를 찾지 못하면 시스템(프로그램)이 종료됨 자바프로그래밍 강원대학교

28 참고 – 자바 예외처리 방법의 장점 (1) 일반 코드로부터 에러처리 코드 분리 readFile { open the file;
determine its size; allocate that much memory; read the file into memory; close the file; } 자바프로그래밍 강원대학교

29 예외처리 방법의 장점 (1) 일반 코드로부터 에러처리 코드 분리 readFile { open the file;
determine its size; allocate that much memory; read the file into memory; close the file; } if the file can't be opened? if the length of the file can't be determined? if enough memory can't be allocated? if the read fails? if the file can't be closed? 자바프로그래밍 강원대학교

30 고전적인 에러 처리 방법 errorCodeType readFile { initialize errorCode = 0;
open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; errorCode = -3; close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; errorCode = errorCode and -4; errorCode = -5; return errorCode; 고전적인 에러 처리 방법 자바프로그래밍 강원대학교

31 readFile throws Exception { open the file; determine its size;
allocate that much memory; read the file into memory; close the file; } 자바프로그래밍 강원대학교

32 예외처리 방법의 장점 (2) Call Stack을 따라서 예외가 전파된다.
method1 { call method2; } method2 { call method3; method3 { call readFile; method1만이 readFile 실행 중 발생할 수 있는 에러를 처리하는 경우 자바프로그래밍 강원대학교

33 고전적인 방법 method1 { errorCodeType error; error = call method2;
if (error) doErrorProcessing; else proceed; } errorCodeType method2 { error = call method3; return error; errorCodeType method3 { error = call readFile; 고전적인 방법 자바프로그래밍 강원대학교

34 method2 throws exception { call method3;
try { call method2; } catch (exception e) { doErrorProcessing; } method2 throws exception { call method3; method3 throws exception { call readFile; Exception (예외) 자바프로그래밍 강원대학교

35 예외처리 방법의 장점 (3) 에러를 묶거나 나눌 수 있다. catch (FileNotFoundException e) { ...
} catch (IOException e) { catch (Exception e) { //A (too) general exception handler e.printStackTrace(); //Output goes to System.err. e.printStackTrace(System.out); //Send trace to stdout. 자바프로그래밍 강원대학교

36 Eclipse에서 데이터파일 위치 프로젝트 폴더가 working folder이다. 이 곳에 in.txt 파일을 만들어 놓는다.
out.txt 파일도 working folder에 만들어진다. 만약 프로젝트 이름이 ch15였다면 workspace\ch15 폴더가 working foler이다. 소스파일들은 workspace\ch15\source 폴더에 위치한다. 새로만들어진 데이터파일이 package explorer 창에 나타나지 않으면 File-Refresh를 해 준다. 자바프로그래밍 강원대학교

37 파일과 스트림 (Files and Streams)
자바프로그래밍 강원대학교

38 텍스트 파일을 읽는 법 – Scanner 이용 Constructors Scanner(File source)
Scanner(InputStream source) Scanner(Readable source) Scanner(String source) 자바프로그래밍 강원대학교

39 텍스트 파일을 읽는 법 – Scanner 이용 중요 methods
Scanner useDelimiter(Pattern pattern) boolean hasNext() - Returns true if this scanner has another token in its input String next() - Finds and returns the next complete token from this scanner boolean nextBoolean() byte nextByte() double nextDouble() float nextFloat() int nextInt() String nextLine() long nextLong() short nextShort() boolean hasNextBoolean() boolean hasNextByte() boolean hasNextDouble() boolean hasNextFloat() boolean hasNextInt() boolean hasNextLine() boolean hasNextLong() boolean hasNextShort() 자바프로그래밍 강원대학교

40 텍스트 파일을 읽는 법 – Scanner 이용 int nextInt()
Throws: (subclasses of RuntimeException) InputMismatchException - if the next token does not match the Integer regular expression, or is out of range NoSuchElementException - if input is exhausted IllegalStateException - if this scanner is closed 자바프로그래밍 강원대학교

41 텍스트 파일을 읽는 법 FileReader reader = new FileReader("input.txt"); Scanner in = new Scanner(reader); File inputFile = new File("input.txt"); Scanner in = new Scanner(inputFile); String in.next String in.nextLine int in.nextInt double in.nextDouble Scanner(File source) Scanner(InputStream source) Scanner(Readable source) Scanner(String source) 자바프로그래밍 강원대학교

42 텍스트 파일에 쓰는 법 – PrintWriter 이용
PrintWriter(File file) PrintWriter(OutputStream out) PrintWriter(String fileName) PrintWriter(Writer out) void println(boolean x) void println(char x) void println(char[] x) void println(double x) void println(float x) void println(int x) void println(long x) void println(Object x) void println(String x) 자바프로그래밍 강원대학교

43 텍스트 파일에 쓰는 법 파일이 이미 존재하는 경우 기존 내용이 지워짐 파일이 존재하지 않는 경우 새 파일이 만들어짐
PrintWriter out = new PrintWriter("output.txt"); 파일이 이미 존재하는 경우 기존 내용이 지워짐 파일이 존재하지 않는 경우 새 파일이 만들어짐 out.println(29.95); out.println(new Rectangle(5, 10, 15, 25)); out.println("Hello, World!"); out.close(); 자바프로그래밍 강원대학교

44 A Sample Program 내 마음은 호수요 그대 저어오오 나는 그대의 흰 그림자를 안고 옥같은 그대의 뱃전에 부서지리라
내 마음은 촛불이요 그대 저 문을 닫아주오 나는 그대의 비단 옷자락에 떨며 최후의 한방울도 남김없이 타오리다 /* 1 */ 내 마음은 호수요 /* 2 */ 그대 저어오오 /* 3 */ 나는 그대의 흰 그림자를 안고 /* 4 */ 옥같은 그대의 뱃전에 부서지리라 /* 5 */ /* 6 */ 내 마음은 촛불이요 ··· 자바프로그래밍 강원대학교

45 File LineNumberer.java
01: import java.io.FileReader; 02: import java.io.IOException; 03: import java.io.PrintWriter; 04: import java.util.Scanner; 05: 06: public class LineNumberer 07: { 08: public static void main(String[] args) 09: { 10: Scanner console = new Scanner(System.in); 11: System.out.print("Input file: "); 12: String inputFileName = console.next(); 13: System.out.print("Output file: "); 14: String outputFileName = console.next(); 15: 16: try 17: { 자바프로그래밍 강원대학교

46 File LineNumberer.java
18: FileReader reader = new FileReader(inputFileName); 19: Scanner in = new Scanner(reader); 20: PrintWriter out = new PrintWriter(outputFileName); 21: int lineNumber = 1; 22: 23: while (in.hasNextLine()) 24: { 25: String line = in.nextLine(); 26: out.println("/* " + lineNumber + " */ " + line); 27: lineNumber++; 28: } 29: 30: out.close(); 31: } 32: catch (IOException exception) 33: { 자바프로그래밍 강원대학교

47 File LineNumberer.java
34: System.out.println("Error processing file:" exception); 35: } 36: } 37: } 자바프로그래밍 강원대학교

48 import java.io.PrintWriter; import java.util.Scanner;
import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class LineNumberer { public static void main(String[] args) Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next(); File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); 자바프로그래밍 강원대학교

49 while (in.hasNextLine()) { String line = in.nextLine();
int lineNumber = 1; while (in.hasNextLine()) { String line = in.nextLine(); out.println("/* " + lineNumber + " */ " + line); lineNumber++; } in.close(); out.close(); 자바프로그래밍 강원대학교

50 File Dialog Boxes 자바프로그래밍 강원대학교

51 File Dialog Boxes JFileChooser chooser = new JFileChooser();
FileReader in = null; if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = chooser.getSelectedFile(); reader = new FileReader(selectedFile); . . . } API 자바프로그래밍 강원대학교

52 Reading Words while (in.hasNext()) { String input = in.next();
System.out.println(input); } White space(space, tab, new line)는 단어구분자 역할을 하며 읽는 과정에서 제거됨 Mary snow. 1729 c++ in.useDelimiter("[^A-Za-z]+"); regular expression (정규식) 자바프로그래밍 강원대학교

53 Processing Lines String line = in.nextLine();
new line을 포함해 한 줄 읽어 new line을 빼고 반환 china India south Korea int i = 0; while (!Character.isDigit(line.charAt(i))) { i++; } String countryName = line.substring(0, i); String population = line.substring(i); countryName = countryName.trim(); int populationValue = Integer.parseInt(population.trim()); 자바프로그래밍 강원대학교

54 Reading Numbers if (in.hasNextDouble()) {
double value = in.nextDouble()); } 자바프로그래밍 강원대학교

55 Reading Numbers nextDouble, nextInt 메소드는 white space를 읽어들이지 않는다.
홍길동 2009 대장금 while (in.hasNextInt()) { int strudentID = in.nextInt(); in.nextLine(); // new line을 지나감 String name = in.nextLine(); ... } 자바프로그래밍 강원대학교

56 Reading Characters Scanner in = new Scanner( ... );
in.useDelimiter(""); while (in.hasNext()) { char ch = in.next().charAt(0); ... } ? 자바프로그래밍 강원대학교

57 명령줄 인자 (Command line arguments)
java LineNumberer input.txt numbered.txt args[0]는 “input.txt”, args[1]은 “numbered.txt” if(args.length >= 1) inputFileName = args[0]; 자바프로그래밍 강원대학교

58 텍스트 형식과 이진데이터 형식 (Text and Binary Formats)
데이터를 저장하는 두 가지 방법 텍스트 형식 (Text format) 이진데이터 형식 (Binary format) 텍스트를 한 글자씩 입출력하기 위해서는 java.io.Reader, java.io.Writer를 사용 이진데이터를 한 바이트씩 입출력하기 위해서는 java.io.InputStream, java.io.OutputStream을 사용 자바프로그래밍 강원대학교

59 텍스트 형식 사람이 읽을 수 있는 형식 정수 12345는 '1' '2' '3' '4' '5' 의 문자들로 표현됨
텍스트 형식 데이터의 입출력을 위해서는 Reader와 Writer 클래스를 사용 FileReader reader = new FileReader("input.txt"); FileWriter writer = new FileWriter("output.txt"); * FileReader, FileWriter는 각각 Reader와 Writer의 서브클래스임 자바프로그래밍 강원대학교

60 텍스트 형식과 이진데이터 형식 (Text and Binary Formats)
자바프로그래밍 강원대학교

61 이진데이터 입출력 InputStream File InputStream Object InputStream OutputStream
PrintStream 자바프로그래밍 강원대학교

62 텍스트데이터 입출력 Reader Writer Input StreamReader Output StreamWriter
PrintWriter FileReader FileWriter 자바프로그래밍 강원대학교

63 이진데이터 형식 (Binary Format)
데이터가 이진수 바이트들로 표현됨 정수 12345는 네 바이트( )로 나타내짐 (48X256+57=12345)  256=2^8 메모리 공간을 더 효율적으로 사용함 입출력을 위해 InputStream과 OutputStream 클래스를 사용함 FileInputStream inputStream = new FileInputStream("input.bin"); FileOutputStream outputStream = new FileOutputStream("output.bin"); 자바프로그래밍 강원대학교

64 이진데이터 파일에서 한 바이트 읽기 read 메소드 다음 바이트를 int 타입으로 반환
end_of_file의 경우 정수 -1 반환 InputStream in = . . .; int next = in.read(); byte b; if (next != -1) b = (byte) next; 자바프로그래밍 강원대학교

65 암호화 프로그램 – 교과서 16.3 (An Encryption Program)
Caesar cipher 1에서 25 사이 숫자 중에서 암호화 키를 선택 암호화 키만큼 각 글자를 이동 예: 만약 키가 3이라면 A는 D로, B는 E로, . . . 자바프로그래밍 강원대학교

66 An Encryption Program 암호를 풀기 위해서는 음수의 암호화 키를 사용 자바프로그래밍 강원대학교

67 To Encrypt Binary Data int next = in.read();
if (next == -1) done = true; else { byte b = (byte) next; byte c = encrypt(b); //call the method to encrypt the byte out.write(c); } 자바프로그래밍 강원대학교

68 File Encryptor.java 01: import java.io.File;
02: import java.io.FileInputStream; 03: import java.io.FileOutputStream; 04: import java.io.InputStream; 05: import java.io.OutputStream; 06: import java.io.IOException; 07: 08: /** 09: An encryptor encrypts files using the Caesar cipher. 10: For decryption, use an encryptor whose key is the 11: negative of the encryption key. 12: */ 13: public class Encryptor 14: { 15: /** 16: Constructs an encryptor. 17: @param aKey the encryption key 18: */ 자바프로그래밍 강원대학교

69 File Encryptor.java 19: public Encryptor(int aKey) 20: {
20: { 21: key = aKey; 22: } 23: 24: /** 25: Encrypts the contents of a file. 26: @param inFile the input file 27: @param outFile the output file 28: */ 29: public void encryptFile(String inFile, String outFile) 30: throws IOException 31: { 32: InputStream in = null; 33: OutputStream out = null; 34: 35: try 36: { 자바프로그래밍 강원대학교

70 File Encryptor.java 37: in = new FileInputStream(inFile);
38: out = new FileOutputStream(outFile); 39: encryptStream(in, out); 40: } 41: finally 42: { 43: if (in != null) in.close(); 44: if (out != null) out.close(); 45: } 46: } 47: 48: /** 49: Encrypts the contents of a stream. 50: @param in the input stream 51: @param out the output stream 52: */ 자바프로그래밍 강원대학교

71 File Encryptor.java 53: public void encryptStream(InputStream in, OutputStream out) 54: throws IOException 55: { 56: boolean done = false; 57: while (!done) 58: { 59: int next = in.read(); 60: if (next == -1) done = true; 61: else 62: { 63: byte b = (byte) next; 64: byte c = encrypt(b); 65: out.write(c); 66: } 67: } 68: } 69: 자바프로그래밍 강원대학교

72 File Encryptor.java 70: /** 71: Encrypts a byte.
70: /** 71: Encrypts a byte. 72: @param b the byte to encrypt 73: @return the encrypted byte 74: */ 75: public byte encrypt(byte b) 76: { 77: return (byte) (b + key); 78: } 79: 80: private int key; 81: } 자바프로그래밍 강원대학교

73 File EncryptorTester.java
01: import java.io.IOException; 02: import java.util.Scanner; 03: 04: /** 05: A program to test the Caesar cipher encryptor. 06: */ 07: public class EncryptorTester 08: { 09: public static void main(String[] args) 10: { 11: Scanner in = new Scanner(System.in); 12: try 13: { 14: System.out.print("Input file: "); 15: String inFile = in.next(); 16: System.out.print("Output file: "); 17: String outFile = in.next(); 자바프로그래밍 강원대학교

74 File EncryptorTester.java
18: System.out.print("Encryption key: "); 19: int key = in.nextInt(); 20: Encryptor crypt = new Encryptor(key); 21: crypt.encryptFile(inFile, outFile); 22: } 23: catch (IOException exception) 24: { 25: System.out.println("Error processing file: " exception); 26: } 27: } 28: } 29: 30: 자바프로그래밍 강원대학교

75 임의 접근과 순차 접근 (Random Access vs. Sequential Access)
file pointer 자바프로그래밍 강원대학교

76 임의접근파일 (RandomAccessFile)
파일을 열 때 모드를 지정함 Reading only ("r") Reading and writing ("rw") file pointer를 옮기는 법 RandomAccessFile f = new RandomAcessFile("bank.dat","rw"); f.seek(n); 자바프로그래밍 강원대학교

77 RandomAccessFile file pointer의 현재 위치를 알아보는 법 파일의 크기를 알아보는 법 (바이트 단위로)
long n = f.getFilePointer(); // of type "long" because files can be very large fileLength = f.length(); 자바프로그래밍 강원대학교

78 A Sample Program – 교과서 16.4 bank account들을 임의접근파일에 저장 텍스트 형식으로 저장한다면?
1001번 계좌에 100원을 저축하면 자바프로그래밍 강원대학교

79 A Sample Program 이진테이터 형식으로 저장한다면? 각 저장소는 고정 길이를 가짐 데이터 저장이 간단함
특정 계좌 위치를 찾기가 쉬움 자바프로그래밍 강원대학교

80 A Sample Program 계좌정보를 RandomAccessFile에 저장!
Account number: readInt and writeInt: 4 bytes Balance: readDouble and writeDouble: 8 bytes 파일에 들어 있는 계좌의 수를 알아내는 법 public int size() throws IOException { return (int) (file.length() / RECORD_SIZE); // RECORD_SIZE is 12 bytes: // 4 bytes for the account number and // 8 bytes for the balance } 자바프로그래밍 강원대학교

81 A Sample Program n 번째 계좌를 읽어 내는 법
public BankAccount read(int n) throws IOException { file.seek(n * RECORD_SIZE); int accountNumber = file.readInt(); double balance = file.readDouble(); return new BankAccount(accountNumber, balance); } 자바프로그래밍 강원대학교

82 A Sample Program n번째 계좌를 파일에 적어 넣는 법
public void write(int n, BankAccount account) throws IOException { file.seek(n * RECORD_SIZE); file.writeInt(account.getAccountNumber()); file.writeDouble(account.getBalance()); } 자바프로그래밍 강원대학교

83 File BankData.java 001: import java.io.IOException;
002: import java.io.RandomAccessFile; 003: 004: /** 005: This class is a conduit to a random access file 006: containing savings account data. 007: */ 008: public class BankData 009: { 010: /** 011: Constructs a BankData object that is not associated 012: with a file. 013: */ 014: public BankData() 015: { 016: file = null; 017: } 자바프로그래밍 강원대학교

84 File BankData.java 018: 019: /** 020: Opens the data file.
019: /** 020: Opens the data file. 021: @param filename the name of the file containing savings 022: account information 023: */ 024: public void open(String filename) 025: throws IOException 026: { 027: if (file != null) file.close(); 028: file = new RandomAccessFile(filename, "rw"); 029: } 030: 031: /** 032: Gets the number of accounts in the file. 033: @return the number of accounts 034: */ 자바프로그래밍 강원대학교

85 File BankData.java 035: public int size() 036: throws IOException
037: { 038: return (int) (file.length() / RECORD_SIZE); 039: } 040: 041: /** 042: Closes the data file. 043: */ 044: public void close() 045: throws IOException 046: { 047: if (file != null) file.close(); 048: file = null; 049: } 050: 자바프로그래밍 강원대학교

86 File BankData.java 051: /** 052: Reads a savings account record.
051: /** 052: Reads a savings account record. 053: @param n the index of the account in the data file 054: @return a savings account object initialized with // the file data 055: */ 056: public BankAccount read(int n) 057: throws IOException 058: { 059: file.seek(n * RECORD_SIZE); 060: int accountNumber = file.readInt(); 061: double balance = file.readDouble(); 062: return new BankAccount(accountNumber, balance); 063: } 064: 065: /** 066: Finds the position of a bank account with a given // number 자바프로그래밍 강원대학교

87 File BankData.java 067: @param accountNumber the number to find
068: @return the position of the account with the given // number, 069: or -1 if there is no such account 070: */ 071: public int find(int accountNumber) 072: throws IOException 073: { 074: for (int i = 0; i < size(); i++) 075: { 076: file.seek(i * RECORD_SIZE); 077: int a = file.readInt(); 078: if (a == accountNumber) // Found a match 079: return i; 080: } 081: return -1; // No match in the entire file 082: } 자바프로그래밍 강원대학교

88 File BankData.java 083: 084: /**
084: /** 085: Writes a savings account record to the data file 086: @param n the index of the account in the data file 087: @param account the account to write 088: */ 089: public void write(int n, BankAccount account) 090: throws IOException 091: { 092: file.seek(n * RECORD_SIZE); 093: file.writeInt(account.getAccountNumber()); 094: file.writeDouble(account.getBalance()); 095: } 096: 097: private RandomAccessFile file; 098: 자바프로그래밍 강원대학교

89 File BankData.java 099: public static final int INT_SIZE = 4;
100: public static final int DOUBLE_SIZE = 8; 101: public static final int RECORD_SIZE 102: = INT_SIZE + DOUBLE_SIZE; 103: } 자바프로그래밍 강원대학교

90 File BankDatatester.java
01: import java.io.IOException; 02: import java.io.RandomAccessFile; 03: import java.util.Scanner; 04: 05: /** 06: This program tests random access. You can access existing 07: accounts and deposit money, or create new accounts. The 08: accounts are saved in a random access file. 09: */ 10: public class BankDataTester 11: { 12: public static void main(String[] args) 13: throws IOException 14: { 15: Scanner in = new Scanner(System.in); 16: BankData data = new BankData(); 17: try 자바프로그래밍 강원대학교

91 File BankDatatester.java
18: { 19: data.open("bank.dat"); 20: 21: boolean done = false; 22: while (!done) 23: { 24: System.out.print("Account number: "); 25: int accountNumber = in.nextInt(); 26: System.out.print("Amount to deposit: "); 27: double amount = in.nextDouble(); 28: 29: int position = data.find(accountNumber); 30: BankAccount account; 31: if (position >= 0) // 기존 계좌인 경우 32: { 33: account = data.read(position); 34: account.deposit(amount); 자바프로그래밍 강원대학교

92 File BankDatatester.java
35: System.out.println("new balance=" 36: account.getBalance()); 37: } 38: else // 새 계좌를 추가하는 경우 39: { 40: account = new BankAccount(accountNumber, 41: amount); 42: position = data.size(); 43: System.out.println("adding new account"); 44: } 45: data.write(position, account); 46: 47: System.out.print("Done? (Y/N) "); 48: String input = in.next(); 49: if (input.equalsIgnoreCase("Y")) done = true; 50: } 51: } 자바프로그래밍 강원대학교

93 File BankDatatester.java
52: finally 53: { 54: data.close(); 55: } 56: } 57: } 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 자바프로그래밍 강원대학교

94 Output Account number: 1001 Amount to deposit: 100 adding new account
Done? (Y/N) N Account number: 1018 Amount to deposit: 200 Amount to deposit: 1000 new balance=1100.0 Done? (Y/N) Y 자바프로그래밍 강원대학교

95 객체 스트림 – 교과서 16.5 (Object Streams)
객체를 있는 그대로 입출력하기 위해 사용 객체 내부의 데이터를 일일이 저장하고 읽어들이는 작업을 하지 않아도 됨 객체 전체를 ArrayList에 넣어 한꺼번에 저장할 수도 있음 이진데이터 형식으로 저장하므로 stream을 사용함 자바프로그래밍 강원대학교

96 BankAccount 객체를 파일에 쓰기 object output stream은 각 객체의 모든 인스턴스 필드를 저장함
BankAccount b = . . .; ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("bank.dat")); out.writeObject(b); 자바프로그래밍 강원대학교

97 BankAccount 객체 읽어오기 readObject 메소드는 Object 타입을 반환함 캐스팅이 필요함
readObject 메소드는 확인예외인 ClassNotFoundException을 던짐 ObjectInputStream in = new ObjectInputStream( new FileInputStream("bank.dat")); BankAccount b = (BankAccount) in.readObject(); 자바프로그래밍 강원대학교

98 객체들을 모아서 저장하기 Write Read
ArrayList<BankAccount> a = new ArrayList<BankAccount>(); // BankAccount 객체들을 a에 넣음 out.writeObject(a); ArrayList<BankAccount> a = (ArrayList<BankAccount>) in.readObject(); 자바프로그래밍 강원대학교

99 Serializable Serializable 인터페이스를 구현한 객체만이 object stream을 통해 입출력될 수 있음
class BankAccount implements Serializable { } 자바프로그래밍 강원대학교

100 Serializable 직렬화(Serialization) 스트림 안에서 각 객체는 일련번호를 부여받음
만약 한 객체가 두 번 저장되면 일련 번호만 두 번 기록됨 자바프로그래밍 강원대학교

101 File Serialtester.java
01: import java.io.File; 02: import java.io.IOException; 03: import java.io.FileInputStream; 04: import java.io.FileOutputStream; 05: import java.io.ObjectInputStream; 06: import java.io.ObjectOutputStream; 07: 08: /** 09: This program tests serialization of a Bank object. 10: If a file with serialized data exists, then it is 11: loaded. Otherwise the program starts with a new bank. 12: Bank accounts are added to the bank. Then the bank 13: object is saved. 14: */ 15: public class SerialTester 16: { 자바프로그래밍 강원대학교

102 File Serialtester.java
17: public static void main(String[] args) 18: throws IOException, ClassNotFoundException 19: { 20: Bank firstBankOfJava; 21: 22: File f = new File("bank.dat"); 23: if (f.exists()) 24: { 25: ObjectInputStream in = new ObjectInputStream 26: (new FileInputStream(f)); 27: firstBankOfJava = (Bank) in.readObject(); 28: in.close(); 29: } 30: else 31: { 32: firstBankOfJava = new Bank(); 33: firstBankOfJava.addAccount(new BankAccount(1001, 20000)); 자바프로그래밍 강원대학교

103 File Serialtester.java
34: firstBankOfJava.addAccount(new BankAccount(1015, 10000)); 35: } 36: 37: // Deposit some money 38: BankAccount a = firstBankOfJava.find(1001); 39: a.deposit(100); 40: System.out.println(a.getAccountNumber() + ":" + a.getBalance()); 41: a = firstBankOfJava.find(1015); 42: System.out.println(a.getAccountNumber() 43: 44: ObjectOutputStream out = new ObjectOutputStream 45: (new FileOutputStream(f)); 46: out.writeObject(firstBankOfJava); 47: out.close(); 48: } 49: } 자바프로그래밍 강원대학교

104 Bank.java public class Bank implements Serializable { public Bank()
accounts = new ArrayList<BankAccount>(); } public void addAccount(BankAccount a) public double getTotalBalance() public int count(double atLeast) public BankAccount find(int accountNumber) public BankAccount getMaximum() private ArrayList<BankAccount> accounts; 자바프로그래밍 강원대학교

105 Output First Program Run Second Program Run 1001:20100.0 1015:10000.0
1001: 1015: 자바프로그래밍 강원대학교


Download ppt "11주 예외처리 (Exception Handling) 파일 입출력 (File Input and Output)"

Similar presentations


Ads by Google