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
09/CArrayErrorApp.java Exceptions 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
09/ExceptionApp.java Exceptions 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. Try Catch Finally 10
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"); 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"); 21
Throw Throwable ü Error = JVM Errors ü Exception = Program Errors ArithmeticException ArrayIndexOutOfBoundsException... Throwable Error Exception 22
Checked VS. Unchecked Unchecked Exceptions ü Compiler does NOT require handlers ü Examples ArithmeticException NullPointerException Checked Exceptions ü Compiler requires handler ü throws keyword ü Examples 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*( ) Class Method (static member) 42
http://www.oracle.com Java API http://docs.oracle.com/javase 43
Java API System class 44
Java API PrintStream class 45
System.out.* System.out.println System.out.print Console Output 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
10/CConsoleOut.java Console Output 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 { FileReaderinputStream = 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
10/CBufferdWriter.java BufferedWriter 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
10/CBufferdReader.java BufferedReader 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");