i/o 프로그래밍

15
I/O 프프프프프 프프프 프프프프 (I) 프프프프 프프프

Upload: stacy-holmes

Post on 30-Dec-2015

52 views

Category:

Documents


0 download

DESCRIPTION

I/O 프로그래밍. 컴퓨터 공학실험 (I) 인공지능 연구실. stream 이해하기. stream 데이터의 소스 (source) 혹은 목적 (destination) 인 입력 또는 출력 장치의 추상적인 표현 프로그램에 입력되거나 또는 프로그램에서 출력되는 바이트 열 (sequence of bytes) 이다 . 자바에서는 stream 을 이용하여 입출력 한다 . Stream programming 의 장점은 데이터의 목적지나 형 (type) 에 관계 없이 데이터를 읽거나 쓰는 알고리즘이 동일하다 . - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: I/O  프로그래밍

I/O 프로그래밍

컴퓨터 공학실험 (I)

인공지능 연구실

Page 2: I/O  프로그래밍

2

stream 이해하기

stream – 데이터의 소스 (source) 혹은 목적 (destination) 인 입력 또는 출력 장치의

추상적인 표현– 프로그램에 입력되거나 또는 프로그램에서 출력되는 바이트 열 (sequence

of bytes) 이다 .– 자바에서는 stream 을 이용하여 입출력 한다 .– Stream programming 의 장점은 데이터의 목적지나 형 (type) 에 관계 없이

데이터를 읽거나 쓰는 알고리즘이 동일하다 .

input stream 과 output stream– input stream : 디스크 파일이나 키보드 또는 원격 컴퓨터 등의 data 를 읽을 때 사용– output stream : 바이트 열이 전송될 수 있는 장치 ( 파일 , 원격 시스템 ) 에 data 를 쓸 때 사용

Page 3: I/O  프로그래밍

3

FileInputStream : FileOutputStream (1)

FileInputStream– 물리적 파일을 읽기 위해서 FileInputStream 객체를 사용– FileInputStream 생성자는 파일이 발견되지 않으면 FileNotFoundExcep

tion 을 발생 시킨다 .

* FileInputStream myStream = new FileInputStream(“C:\data\aaa.txt”) ;

FileOutputStream– 물리적 파일에 쓰기 위해서 FileOutputStream 객체를 사용– 파일에 대해 쓰기가 허가되지 않으면 SecurityException 을

발생시킨다 .

* FileOutputStream myStream = new FileOutputStream(“bbb.txt”) ;

Page 4: I/O  프로그래밍

4

FileInputStream : FileOutputStream (2)1. import java.io.*; // command line argument 로 파일이름 입력 받아 다른 // 이름의 파일로 copy1. public class FileCopy {2. public static void main(String [] args) throws Exception {3. if (args.length < 2) { 4. System.out.println("Usage : java CopyFile file1 file2");5. return;6. }7. FileInputStream fis= new FileInputStream(args[0]); // 입력받은 첫 번째 파일 읽고8. FileOutputStream fos = new FileOutputStream(args[1]); // 입력받은 두 번째 파일에 복사

9. int readByte = 0; 10. while ((readByte = fis.read()) != -1) { // EOF 까지 1byte 를 읽는다11. fos.write(readByte); // 1 byte 를 쓴다12. }13. fis.close();14. fos.close();15. System.out.println(args[0] + " copied to " + args[1]);16. }17. }

Page 5: I/O  프로그래밍

5

DataInputStream : DataOutputStream (1)

FileInputStream, FileOutputStream - 주로 byte 단위의 I/O 에 사용

DataInputStream, DataOutputStream - 주로 primitive I/O 가 필요할 경우에 사용

Java 는 문자나 문자열을 다룰 때 16bit-UniCode 방식을 사용– 한글은 byte 단위로 I/O 하게 되면 글자 자체가 깨질 위험이 있다 .

( 한글 => 2byte)

– I/O 할 때 이렇게 16bit-Unicode를 사용하는 I/O class 들을 사용한다 .

Reader, Writer – 내부적으로 읽어 들인 데이터를 2byte 조합으로 사용하는 stream

Page 6: I/O  프로그래밍

6

DataInputStream : DataOutputStream (2)

Method summarywriteByte(int value) Int 인수의 하위 바이트를 스트림에 쓴다 .

writeBoolean(boolean value)

Boolean 값이 true 이면 1 을 , false 이면 0 을 스트림에 한 바이트 단위로 쓴다 .

writeChar(int value) 인수의 하위 두 바이트를 스트림에 쓴다 .

writeShort(int value) 인수의 하위 두 바이트를 스트림에 쓴다 .

writeInt(int value) int 인수의 네 바이트 전체를 스트림에 쓴다 .

writeLong(long value) Long 인수의 여덟 바이트 전체를 스트림에 쓴다 .

writeFloat(float value) Float 인수의 네 바이트를 스트림에 쓴다 .

writeDouble(double value) Double 인수의 여덟 바이트를 스트림에 쓴다 .

DataOutputStream Class Method summary

Page 7: I/O  프로그래밍

7

DataInputStream : DataOutputStream (3)1. import java.io.*; // 파일에 문자를 기록하고 기록된 문자를 읽어 화면에 출력2. public class ExDataStream {3. public static void main(String [] args) throws Exception {4. if (args.length < 1 ) {5. System.out.println(" 실행방법 : java ExDataStream.java aa.txt");6. return;7. }8. FileOutputStream fos = new FileOutputStream(args[0]);9. DataOutputStream dos = new DataOutputStream(fos); //privitive type size 의 i/o 에 이용10. dos.writeUTF(" 홍길동 "); // UTF-8 encoding 으로 파일에 기록11. dos.writeUTF("41456"); // UTF-8 은 16bit 유니코드를 8bit 문자로 변경 12. dos.writeInt(30);13. dos.close();14. FileInputStream fis = new FileInputStream(args[0]);15. DataInputStream dis = new DataInputStream(fis);16. System.out.println(" 이름 : " + dis.readUTF()); // 파일의 내용을 읽어서 출력17. System.out.println(" 번호 : " + dis.readUTF());18. System.out.println(" 나이 : " + dis.readInt());19. dis.close();20. }21. }

Page 8: I/O  프로그래밍

8

reader : writer

1. import java.io.*; // 키보드로부터 문자열을 입력 받아 파일에 저장2. public class StringInput {3. public static void main(String [] args) throws Exception {4. String inputString;5. InputStreamReader isr = new InputStreamReader(System.in);6. BufferedReader br = new BufferedReader(isr);7. FileOutputStream fos = new FileOutputStream(args[0]);8. OutputStreamWriter osr = new OutputStreamWriter(fos);9. BufferedWriter bw = new BufferedWriter(osr);10. inputString = br.readLine(); //readLine() 은 엔터를 치기 전까지 입력한 내용을

버퍼 에 읽어 온다 .

11. 12. bw.write(inputString + "\n"); // 버퍼의 내용을 쓴다13. bw.close(); // 생성한 모든 stream object 을 close 할 필요 없이 최종 stream objec

t 만 close 하면 된다 .

14. br.close();15. }16. }

Page 9: I/O  프로그래밍

9

File Class

File Class– File Object 는 스트림이 아니라 하드 디스크 상의 물리적 파일이나

디렉토리로의 경로명을 나타낸다 .

– File Object 는 파일 뿐만 아니라 디렉토리도 가리킬 수 있다 .

– 파일이나 디렉토리로의 경로명을 나타내는 객체를 만들 수 있게 해주고 , 만든 객체를 테스트 할 수 있는 여러 가지 메소드를 제공한다 .

Method summaryexists() File 객체가 참조하는 파일이나 디렉토리가 존재하면 true,

아니면 false 리턴

isDirectory() File 객체가 디렉토리를 참조하면 true, 아니면 false 리턴

isFile() File 객체가 파일을 참조하면 true, 아니면 false 리턴

canRead() File 객체가 참조하는 파일을 읽을 수 있으면 true, 아니면 false 리턴한다 . 파일에 대한 읽기 SecurityException 을 발생시킬 수 있다 .

canWrite() File 객체가 참조하는 파일을 쓸 수 있으면 true, 아니면 false 리턴 한다 . 파일에 쓸 수 없으면 SecurityException 을 발생시킬 수 있다 .

Page 10: I/O  프로그래밍

10

URL Class URL Class

– Java.net 패키지에 정의 되어 있다 .– URL 객체는 특정 URL 에 대한 정보를 가지고 있으며 , 네트워크 상에서 어디에

있든지 접근하거나 읽을 수 있다 .– URL 은 데이터의 위치를 나타내는 경로의 확장된 형태라고 할 수 있다 .– 인터넷 상의 URL 을 local pc 의 파일처럼 다룰 수 있다 .

1. import java.io.*; // 인터넷 상의 원하는 페이지를 읽어오는 예제2. import java.net.*; //URL Class 사용하기위해 반드시 import 한다 .3. public class GetIndexHtml {4. public static void main(String [] args) throws Exception {5. byte [] inputString = new byte[1024];6. InputStream is = (new URL(args[0])).openStream(); 7. FileOutputStream fos = new FileOutputStream(args[1]);8. while(is.read(inputString, 0, inputString.length) != -1) {9. fos.write(inputString);10. }11. fos.close();12. }13. }

Page 11: I/O  프로그래밍

11

RandomAccessFile(1)

RandomAccessFile– 파일을 임의로 액세스할 때 사용– 앞으로 , 뒤로 움직이면서 원하는 부분에 접근할 수 있는 기능 (Rand

omAccess) 을 제공 * RandomAccessFile raf = new RandomAccessFile("c:\myfile.txt", "r/w");

Method summaryseek(long pos) 파일의 현재 위치를 pos 인수가 지정한 위치로 옮긴다

getFilePointer() 파일의 현재 위치 ( 파일의 시작으로부터의 변위 ) 를 long 유형으로 리턴한다 .

length() 파일의 길이를 바이트 단위의 long 유형값으로 리턴한다 .

Page 12: I/O  프로그래밍

12

RandomAccessFile(2)

1. import java.io.*;

2. import java.util.*;

3. public class RandomWrite{

4. public static void main(String [] args) throws Exception {

5. RandomAccessFile raf = new RandomAccessFile("Mylog.log", "rw");

6. raf.seek(raf.length()); // 파일의 가장 마지막으로 현재 위치를 옮긴다 .

7. raf.writeUTF(new Date().toString()); // 현재 날짜를 쓴다 .

8. raf.close();

9. }

10. }

Page 13: I/O  프로그래밍

13

Serialization(1)

Serialization– 객체를 외부 파일에 저장하고 읽어 오는 과정– 자바에서 제공하는 기본 데이터 type 이외에도 여러 객체들을

스트림에 쓰고 읽을 수 있는 기능을 제공– serializable 이 될 수 있는 object 의 class 는 Serializable 이라고 하는

interface 를 반드시 implements 해야 한다 .

Serializable interface– serializable interface implements 할 method 가 없다 .

– Serializable 을 implements 한다는 것은 이 class 가 serializable 이 가능하다는 의미한다 .

– Object 가 serialization 될 때 data 부분 (member 변수 ) 만 저장되며 constructor 나 method 의 code 는 저장되지 않는다 .

Page 14: I/O  프로그래밍

14

Serialization(2)1. import  java.io.*; //primitive type 이 아닌 object 를 파일에 읽고 쓰는 예제2.  public class TestSerialization implements Serializable { 3.          String name;4.           int age = 7;5.          TestSerialization (String name, int age) {6.                       this.name = name;7.                       this.age = age;8.       }9. }

1. public class SerializeMyObject { //TestSerialization class 의 object 를 파일에 write 예제2.             TestSerialization ts;3.               public static void main(String [] args) throws Exception {4.                           SerializeMyObject smo = new SerializeMyObject();5.                           smo.writeMyObject(); // object 를 file 로 write 함 .6.                           smo.ts = null; // object 를 memory 에서 없앰 .7.                           smo.readMyObject(); // 파일에서 object 를 다시 읽어옴 .8.                           System.out.println(smo.ts.name);9.               }

Page 15: I/O  프로그래밍

15

Serialization(3)

1.        public void writeMyObject() throws Exception { //object 를 파일에 write2.                  ts = new TestSerialization(" 홍길동 ", 32);3.                  ObjectOutputStream oos =4.                   new ObjectOutputStream(new FileOutputStream("myObject.txt"));5.                   oos.writeObject(ts); // object 를 파일로 write 함 .6.                   oos.close();7.         }8.  9.         public void readMyObject() throws Exception { // 파일에 저장된 object 를 읽어 // 메모리에 올리는 메서드1.                  ObjectInputStream ois =2.                  new ObjectInputStream(new FileInputStream("myObject.txt"));3.                  ts = (TestSerialization)ois.readObject(); // object 를 파일에서 읽어서 memory 에

올림 .

4.                  ois.close();5.         }6. }