Download Exception and File I/O

Document related concepts
no text concepts found
Transcript
JAVA Programming
Spring, 2016
Dongwoo Kang
Contents
Exceptions
Overview
try, catch, finally, throws, throw
exception classes
3
Exceptions
Exception = Runtime Error
ü
잘못된 코드, 부정확한 데이터, 예외적인 상황에 의하
여 발생하는 오류
§ 0으로 나누는 작업
Goal = Fail Gracefully
Exception Handling
ü
ü
ü
Structured
Controlled
Object-Oriented
4
Error case
5
Exceptions
09/CArrayErrorApp.java
1.public class CArrayErrorApp {
2.
public static void main(String[] args) {
3.
int nums[] = new int[4];
4.
5.
System.out.println("Before - array access");
6.
nums[7] = 10;
7.
System.out.println("After - array access");
8.
}
9.}
java CArrayErrorApp
Before - array access
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 7
at CArrayErrorApp.main(CArrayErrorApp.java:7)
6
예외처리
오류가 발생했을 때 오류를 사용자에게 알려주고
모든 데이터를 저장하게 한 후에 사용자가 우아하
게(gracefully) 프로그램을 종료할 수 있도록 하는
것이 바람직하다
Exceptions
Keywords
ü
ü
ü
try
catch
finally
1.try {
2. ...
3.}
4.catch (Exception e)
{
5. ...
6.}
7.finally {
8. ...
9.}
Classes
8
Exceptions
09/ExceptionApp.java
1.class ExceptionDemo {
2.
public static void main(String[] args) {
3.
int nums[] = new int[4];
4.
5.
try {
6.
System.out.println("Something bad is about to happen.");
7.
nums[7] = 10;
8.
System.out.println("This never executes. ");
9.
}
10.
11.
catch (ArrayIndexOutOfBoundsException exc){
12.
System.out.println("Array index out of bounds. ");
13.
return;
14.
}
15.
16.
finally {
17.
System.out.println("Cleaning up in finally block.");
18.
}
19.
}
20.}
9
Exceptions
Results
E:\java\Class\09>java CArrayExecptionApp
Something bad is about to happen.
Array index out of bounds.
Cleaning up in finally block.
10
Try
Catch
Finally
try/catch/finally 블록에서의 실행 흐름
12
Exception e
ü
e.getMessage( ), e.toString( ), e.printStackTrace( )
13
Exception 종류
ArithmeticException : 어떤 수를 0으로 나누는 것과 같이 비정상 계산 중 발
생
ArrayIndexOutOfBoundsException : 배열 참조가 범위를 벗어 났을 때 발생
NullPointerException : NULL 객체 참조 시 발생
IllegalArgumentException : 메소드의 전달 인자값이 잘못될 경우 발생
IllegalStateException : 객체의 상태가 메소드 호출에는 부적합할 경우 ㅂ라
생
IndexOutOfBoundsException : index 값이 범위를 넘어갈 경우 발생
UnsupportedOperationException : 객체가 메소드를 지원하지 않는 경우
발생
SecurityException : 보안 위반 발생 시 보안 관리 프로그램에서 발생
ClassNotFoundException : 지정된 클래스가 없을 경우 발생
IOException : 파일 입 출력 예외
ProviderException, NoSuchElementException, ArrayStoreException, Cl
assCastException, EmptyStackException
14
15
다형성과 예외
다형성의 원칙에 따라 상위 클래스의 참조 변수는
하위 클래스의 객체를 참조할 수 있다.
특히 이것은 catch 블록에서 예외를 잡을 때 유용
하다.
다형성과 예외
try {
getInput();
// 예외를 발생하는 메소드
}
catch(NumberException e) {
// NumberException의 하위 클래스를 모두 잡을 수 있다.
}
try {
getInput();
}
catch(Exception e) {
//Exception의 모든 하위 클래스를 잡을 수 있으나 분간할 수 없다.!
}
다형성과 예외
try {
getInput();
}
catch(TooSmallException e) {
//TooSmallException만 잡힌다.
}
catch(NumberException e) {
//TooSmallException을 제외한 나머지 예외들이 잡힌다.
}
try {
getInput();
}
catch(NumberException e) {
//모든 NumberException이 잡힌다.
}
catch(TooSmallException e) {
//아무 것도 잡히지 않는다!
}
JDK 7 이후 변경사항(1)
Catching Multiple Exception
19
JDK 7 이후 변경사항(1)
Automatic Resource Management
ü
try-with-resources
ArrayList<String> list = new ArrayList<String>();
list.add(“item1”);
list.add(“item2”);
list.add(“item3”);
try (PrintWriter output = new PrintWriter("myoutput.txt")) {
for (String s : list) {
output.println(s.toLowerCase());
}
}
20
public static void main(String args[]) {
FileInputStream fin = null;
BufferedReader br = null;
try {
fin = new FileInputStream("info.xml");
br = new BufferedReader(new InputStreamReader(
fin));
if (br.ready()) {
String line1 = br.readLine();
System.out.println(line1);
}
} catch (FileNotFoundException ex) {
System.out.println("Info.xml is not found");
} catch (IOException ex) {
System.out.println("Can't read the file");
} finally {
try {
if (fin != null)
fin.close();
if (br != null)
br.close();
} catch (IOException ie) {
System.out.println("Failed to close files");
}
}
}
21
public static void main(String args[]) {
try (FileInputStream fin = new FileInputStrea
m("info.xml");
BufferedReader br = new BufferedRead
er(new InputStreamReader(
fin));) {
if (br.ready()) {
String line1 = br.readLine();
System.out.println(line1);
}
} catch (FileNotFoundException ex) {
System.out.println("Info.xml is not found");
} catch (IOException ex) {
System.out.println("Can't read the file");
}
}
Throw
Throwable
ü
ü
Error = JVM Errors
Exception = Program Errors
§ ArithmeticException
§ ArrayIndexOutOfBoundsException
§ ...
Throwable
Error
22
Exception
Checked VS. Unchecked
Checked Exceptions
Unchecked Exceptions
ü
ü
Compiler does NOT
require handlers
Examples
ü
Compiler requires
handler
throws keyword
ü
Examples
ü
§ ArithmeticException
§ NullPointerException
§ IOException
§ …
23
throws
예외가 발생한 메소드를 호출한 지점으로 예외를
전달하여 처리
메소드B가 메소드A를 호출 했을 때
24
25
public void writeList() throws IOException {
PrintWriter = new PrintWriter(new FileWriter("outfile.txt"));
for (int i = 0; i < SIZE; i++)
out.println("배열 원소 " + i + " = " + list[i]);
out.close();
}
26
LAB: 예외 처리하기
다음 코드의 예외를 처리하여 보자.
public class Test {
public static void main(String[] args) {
System.out.println(readString());
}
public static String readString() {
byte[] buf = new byte[100];
System.out.println("문자열을 입력하시오:");
System.in.read(buf);
return new String(buf);
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException
at Test.readString(Test.java:9)
at Test.main(Test.java:3)
SOLUTION
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try {
System.out.println(readString());
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static String readString() throws IOException {
byte[] buf = new byte[100];
System.out.println("문자열을 입력하시오:");
System.in.read(buf);
return new String(buf);
}
}
에외 생성하기
예외는 throw 문장으로 생성된다.
어떤 메소드도 throw 문장을 사용하여서 예외를
생성할 수 있다.
throw 문장은 하나의 인수만을 요구하는데 바로
Throwable 객체이다.
Throwable 객체는 Throwable 클래스를 상속 받는
자식 클래스들의 인스턴스
예제
public Object pop() {
Object obj;
if (size == 0) {
throw new EmptyStackException();
}
...
return obj;
}
32
33
assertions
단언(assertions)은 프로그래머가 현재 시점에서
믿고 있는 내용을 다시 한 번 확인할 때 사용된다.
34
import java.util.Scanner;
public class AssertionTest {
public static void main(String argv[]) {
Scanner input = new Scanner(System.in);
System.out.print("날짜를 입력하시오: ");
int date = input.nextInt();
// 날짜가 1 이상이고 31 이하인지를 검증한다.
assert(date >= 1 && date <= 31) : "잘못된 날짜: " + date;
System.out.printf("입력된 날짜는 %d입니다.\n", date);
}
}
35
로깅
로깅(logging)이란 어딘가에 계속하여 기록을 남
기는 것이다.
예제
im port java.util.logging.Logger;
public class LoggingTest {
public static void main(String argv[]) {
String filename = "test.dat";
Logger.getGlobal().info(filename + " 파일을 오픈하였음 ");
}
}
8월 15, 2015 1:48:39 오후 LoggingTest main
정보: test.dat 파일을 오픈하였음
Overview
byte streams, character streams,
file I/O wrapper classes
38
파일의 필요성
스트림(stream)
스트림(stream)은 “순서가 있는 데이터의 연속적
인 흐름”이다.
스트림은 입출력을 물의 흐름처럼 간주하는 것이
다.
Predefined Streams
System.out
ü
Console
System.in
ü
Keyboard
System.err
ü
Console
41
What is Stream ?
import java.lang.*;
System.out.print*( )
Method
Class
(static member)
42
Java API
http://www.oracle.com
http://docs.oracle.com/javase
43
Java API
System class
44
Java API
PrintStream class
45
Console Output
System.out.*
System.out.println
System.out.print
System.out.printf(format-string”, [arg1, arg2…])
Converter
Meaning
%d
Decimal integer
%o
Octal
%x
Hexadecimal
%f
floating-point number
%c
Capital C will uppercase the lette
%s
Capital S will uppercase all the letters in the string
%h
A hashcode is like an address
46
Console Output
10/CConsoleOut.java
1.public class CConsoleOut {
2.
public static void main(String[] args) {
3.
System.out.print("Hello World\n");
4.
System.out.println("Hello World.");
5.
System.out.printf("Starwars %d, %d, %d\n", 1, 2, 3);
6.
System.out.printf("1/2 = %f, %d, %c\n", 0.5, 5, 'A');
7.
String s = "Hello World";
8.
System.out.printf("The String object \'%s\‘
9.
is at hash code: %h\n", s, s);
10. }
11.}
47
Console Output
Results
E:\java\Class\10>java CConsoleOut
Hello World
Hello World.
Starwars 1, 2, 3
1/2 = 0.500000, 5, A
The String object 'Hello World' is at hash code:
cc969a84
48
스트림의 분류
입출력의 단위에 따라서 분류
바이트 스트림과 문자 스트림
바이트 스트림(byte stream)은 바이트 단위로 입출력
하는 클래스
바이트 스트림 클래스들은 추상 클래스인
InputStream와 OutputStream에서 파생된다.
바이트 스트림 클래스 이름에는InputStream(입력)과
OutputStream(출력)이 붙는다.
문자 스트림(character stream)은 문자 단위로 입출력
하는 클래스
이들은 모두 기본 추상 클래스인 Reader와 Write 클래
스에서 파생된다.
문자 스트림 클래스 이름에는 Reader(입력)와 Writer(
출력)가 붙는다.
바이트 스트림
문자 스트림
기본적인 메소드
InputStream 클래스
ü
abstract int read() - 한 바이트를 읽어서 반환한다(0에
서 255 사이의 정수).
OutputStream 클래스
ü
abstract void write(int b) - 한 바이트를 특정한 장치에
쓴다.
Reader 클래스
ü
abstract int read() - 한 문자를 읽어서 반환한다.
Writer 클래스
ü
abstract void write(int c) - 한 문자를 특정한 장치에 쓴
다.
FileInputStream과 FileOutputStream
파일이 입출력 대상이 된다.
LAB: SimplePair 클래스 작성하기
56
LAB: SimplePair 클래스 작성하기
input.txt
The language of truth is simple.
Easier said than done.
First think and speak.
Translators, traitors.
No smoke without fire.
output.txt
The language of truth is simple.
Easier said than done.
First think and speak.
Translators, traitors.
No smoke without fire.
예제 설명
LAB: 이미지 파일 복사하기
하나의 이미지 파일을 다른 이미지 파일로 복사하
는 프로그램을 작성하여 보자.
LAB: SimplePair 클래스 작성하기
public class ByteStreamsLab {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.print("원본 파일 이름을 입력하시오: ");
String inputFileName = scan.next();
System.out.print("복사 파일 이름을 입력하시오: ");
String outputFileName = scan.next();
try (InputStream inputStream = new
FileInputStream(inputFileName);
OutputStream outputStream = new
FileOutputStream(outputFileName)) {
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
}
System.out.println(inputFileName + "을 " + outputFileName
+ "로 복사하였습니다. ");
}
}
파일 문자 스트림
예제
public class CopyFile2 {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("input.txt");
outputStream = new FileWriter("output.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
스트림들은 연결될 수 있다.
예제
FileInputStream fileSt = new FileInputStream("sample.dat");
DataInputStream dataSt = new DataInputStream(fileSt);
int i = dataSt.readInt();
DataInputStream 과 DataOutputStream
DataInputStream 과 DataOutputStream 클래스는
기초 자료형 단위로 데이터를 읽고 쓸 수 있다.
DataInputStream 클래스는 readByte(), readInt(),
readDouble()과 같은 메소드들을 제공한다.
DataOutputStream 클래스는 writeByte(int v),
writeInt(int v), writeDouble(double v)와 같은 메소
드들을 제공한다.
66
67
버퍼 스트림
inputStream = new BufferedReader(new FileReader("input.txt"));
outputStream = new BufferedWriter(new FileWriter("out put.txt"));
BufferedReader & BufferedWriter
BufferedReader
ü
Reader Class
// java.io.BufferedReader
1. BufferedReader(Reader in); // Constructor
2. public String readLine() throws IOException
BufferedWriter
ü
Writer Class
// java.io.BufferedWriter
1. BufferedWriter(Writer out); // Constructor
2. public void write(String str) throws IOException
69
BufferedWriter
10/CBufferdWriter.java
1.package com.jkpark.java.CBufferdWriter;
2.import java.io.*;
3.
4.public class CBufferdWriter {
5.
6.
public static void main(String[] args)
throws IOException {
6.
BufferedWriter outStream =
new BufferedWriter(new FileWriter("star.txt"));
7.
8.
outStream.write("Star wars");
9.
outStream.newLine();
10.
outStream.write("A long time ago, in a galaxy far, far away....\n");
11.
outStream.write("It is a period of civil war. Rebel\n");
12.
13.
outStream.close();
14.
System.out.println("star.txt is written.");
15.
}
16.}
70
BufferedReader
10/CBufferdReader.java
1.package com.jkpark.java.CBufferedReader;
2.import java.io.*;
3.
4.public class CBuffedReader {
5.
6.
public static void main(String[] args)
throws IOException {
6.
String szBuf;
7.
BufferedReader inStream =
new BufferedReader(new FileReader ("star.txt"));
8.
9.
while (true) {
10.
szBuf = inStream.readLine();
11.
12.
if(szBuf == null) break;
13.
14.
System.out.println(szBuf);
15.
}
16.
inStream.close();
17. }
18.}
71
브릿지 스트림
문자 Encoding
자바에서는 StandardCharsets 클래스 안에 각
Encoding 방법이 StandardCharsets.UTF_8,
StandardCharsets.UTF_16과 같이 상수로 정의되
어 있다.
String s = new String(100,
StandardCharsets.UTF_8 );
파일에서 읽을 때는 InputStreamReader 클래스를
사용한다.
Encoding
InputStreamReader Class
BufferedReader reader = new BufferedReader(new InputStreamRea
der(new FileInputStream(filepath),"UTF8"));
74
예제
public class CharEncodingTest {
public static void main(String[] args) throws IOException {
File fileDir = new File("input.txt");
BufferedReader in = new BufferedReader(new
InputStreamReader(
new FileInputStream(fileDir), "UTF8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
}
}
75
ObjectInputStream과 ObjectOutputStream
직렬화(serialization):
ü
객체가 가진 데이터들을 순차적인 데이터로 변환하는
것
예제
import java.io.*;
import java.util.Date;
public class ObjectStreamTest {
public static void main(String[] args) throws IOException {
ObjectInputStream in = null;
ObjectOutputStream out = null;
try {
int c;
out = new ObjectOutputStream(new
FileOutputStream("object.dat"));
out.writeObject(new Date());
객체를 직렬화하
여서 쓴다.
out.flush();
in = new ObjectInputStream(new FileInputStream("object.dat"));
Date d = (Date) in.readObject();
System.out.println(d);
예제
} catch (ClassNotFoundException e) {
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Mon Jul 13 13:39:47 KST 2015
파일 정보를 얻으려면
Path 클래스는 경로를 나타내는 클래스로서
“/home/work”와 같은 경로를 받아서 객체를 반환
한다.
(예) Path workDirectory =
Paths.get("C:\home\work");
File 객체는 파일이 아닌 파일 이름을 나타낸다.
(예) File file = new File("data.txt");
예제
public clas s FileTest {
public static void main(String[] args) throws IOException {
String name = "c:/eclipse";
File dir = new File(name);
String[] fileNames = dir.list(); // 현재 디렉토리의 전체 파일 리스트
for (String s : fileNames) {
File f = new File(name + "/" + s); // 절대 경로로 이름을
주어야 함
System.out.println("===============================");
System.out.println("이름: " + f.getName());
System.out.println("경로: " + f.getPath());
System.out.println("부모: " + f.getParent());
System.out.println("절대경로: " + f.getAbsolutePath());
System.out.println("정규경로: " + f.getCanonicalPath());
System.out.println("디렉토리 여부:" + f.isDirectory());
System.out.println("파일 여부:" + f.isFile());
System.out.println("===============================");
}
}
}
예제
===============================
이름: .eclipseproduct
경로: c:\eclipse\.eclipseproduct
부모: c:\eclipse
절대경로: c:\eclipse\.eclipseproduct
정규경로: C:\eclipse\.eclipseproduct
디렉토리 여부:false
파일 여부:true
===============================
LAB: 이미지 파일에서 RGB 값 구하기
이미지 파일에서 픽셀 값을 읽어서 그레이스케일
이미지로 변환한 후에 저장하여 보자.
예제
public class RGB2Gray {
BufferedImage myImage;
int width;
int height;
public RGB2Gray() {
File ifile = new File("test.jpg");
try {
myImage = ImageIO.read(ifile);
} catch (IOException e) {
e.printStackTrace();
}
width = myImage.getWidth();
height = myImage.getHeight();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
예제
green + blue, red + green + blue);
Color c = new Color(myImage.getRGB(x, y));
int red = (int) (c.getRed() * 0.299);
int green = (int) (c.getGreen() * 0.587);
int blue = (int) (c.getBlue() * 0.114);
Color gray = new Color(red + green + blue, red +
myImage.setRGB(x, y, gray.getRGB());
}
}
File ofile = new File("gray.jpg");
try {
ImageIO.write(myImage, "jpg", ofile);
} catch (IOException e) {
e.printStackTrace();
}
}
static public void main(String args[]) throws Exception {
RGB2Gray obj = new RGB2Gray();
}
}
임의 접근 파일
임의 접근 파일은 파일에 비순차적인 접근을 가능
하게 한다.
new RandomAccessFile("all.zip", "r");
Related documents