1 / 15

I/O 프로그래밍

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

Télécharger la présentation

I/O 프로그래밍

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. I/O 프로그래밍 컴퓨터 공학실험(I) 인공지능 연구실

  2. stream 이해하기 • stream • 데이터의 소스(source) 혹은 목적(destination)인 입력 또는 출력 장치의 추상적인 표현 • 프로그램에 입력되거나 또는 프로그램에서 출력되는 바이트 열(sequence of bytes)이다. • 자바에서는 stream을 이용하여 입출력 한다. • Stream programming의 장점은 데이터의 목적지나 형(type)에 관계 없이 데이터를 읽거나 쓰는 알고리즘이 동일하다. • input stream과 output stream • input stream : 디스크 파일이나 키보드 또는 원격 컴퓨터 등의 data를 읽을 때 사용 • output stream : 바이트 열이 전송될 수 있는 장치(파일, 원격 시스템)에 data를 쓸 때 사용

  3. FileInputStream : FileOutputStream (1) • FileInputStream • 물리적 파일을 읽기 위해서 FileInputStream 객체를 사용 • FileInputStream 생성자는 파일이 발견되지 않으면 FileNotFoundException을 발생 시킨다. * FileInputStream myStream = new FileInputStream(“C:\data\aaa.txt”) ; • FileOutputStream • 물리적 파일에 쓰기 위해서 FileOutputStream 객체를 사용 • 파일에 대해 쓰기가 허가되지 않으면 SecurityException을 발생시킨다. * FileOutputStream myStream = new FileOutputStream(“bbb.txt”) ;

  4. FileInputStream : FileOutputStream (2) • import java.io.*; // command line argument로 파일이름 입력 받아 다른 // 이름의 파일로 copy • public class FileCopy { • public static void main(String [] args) throws Exception { • if (args.length < 2) { • System.out.println("Usage : java CopyFile file1 file2"); • return; • } • FileInputStream fis= new FileInputStream(args[0]); //입력받은 첫 번째 파일 읽고 • FileOutputStream fos = new FileOutputStream(args[1]); //입력받은 두 번째 파일에 복사 • int readByte = 0; • while ((readByte = fis.read()) != -1) { // EOF까지 1byte를 읽는다 • fos.write(readByte); // 1 byte를 쓴다 • } • fis.close(); • fos.close(); • System.out.println(args[0] + " copied to " + args[1]); • } • }

  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

  6. DataInputStream : DataOutputStream (2) • DataOutputStream Class Method summary

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

  8. reader : writer • import java.io.*; //키보드로부터 문자열을 입력 받아 파일에 저장 • public class StringInput { • public static void main(String [] args) throws Exception { • String inputString; • InputStreamReader isr = new InputStreamReader(System.in); • BufferedReader br = new BufferedReader(isr); • FileOutputStream fos = new FileOutputStream(args[0]); • OutputStreamWriter osr = new OutputStreamWriter(fos); • BufferedWriter bw = new BufferedWriter(osr); • inputString = br.readLine(); //readLine()은 엔터를 치기 전까지 입력한 내용을 버퍼 에 읽어 온다. • bw.write(inputString + "\n"); //버퍼의 내용을 쓴다 • bw.close(); //생성한 모든 stream object을 close할 필요 없이 최종 stream object만 close하면 된다. • br.close(); • } • }

  9. File Class • File Class • File Object는 스트림이 아니라 하드 디스크 상의 물리적 파일이나 디렉토리로의 경로명을 나타낸다. • File Object는 파일 뿐만 아니라 디렉토리도 가리킬 수 있다. • 파일이나 디렉토리로의 경로명을 나타내는 객체를 만들 수 있게 해주고, 만든 객체를 테스트 할 수 있는 여러 가지 메소드를 제공한다.

  10. URL Class • URL Class • Java.net 패키지에 정의 되어 있다. • URL객체는 특정 URL에 대한 정보를 가지고 있으며, 네트워크 상에서 어디에 있든지 접근하거나 읽을 수 있다. • URL은 데이터의 위치를 나타내는 경로의 확장된 형태라고 할 수 있다. • 인터넷 상의 URL을 local pc의 파일처럼 다룰 수 있다. • import java.io.*; // 인터넷 상의 원하는 페이지를 읽어오는 예제 • import java.net.*; //URL Class사용하기위해 반드시 import한다. • public class GetIndexHtml { • public static void main(String [] args) throws Exception { • byte [] inputString = new byte[1024]; • InputStream is = (new URL(args[0])).openStream(); • FileOutputStream fos = new FileOutputStream(args[1]); • while(is.read(inputString, 0, inputString.length) != -1) { • fos.write(inputString); • } • fos.close(); • } • }

  11. RandomAccessFile(1) • RandomAccessFile • 파일을 임의로 액세스할 때 사용 • 앞으로, 뒤로 움직이면서 원하는 부분에 접근할 수 있는 기능(RandomAccess)을 제공 * RandomAccessFile raf = new RandomAccessFile("c:\myfile.txt", "r/w");

  12. RandomAccessFile(2) • import java.io.*; • import java.util.*; • public class RandomWrite{ • public static void main(String [] args) throws Exception { • RandomAccessFile raf = new RandomAccessFile("Mylog.log", "rw"); • raf.seek(raf.length()); //파일의 가장 마지막으로 현재 위치를 옮긴다. • raf.writeUTF(new Date().toString()); //현재 날짜를 쓴다. • raf.close(); • } • }

  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는 저장되지 않는다.

  14. Serialization(2) • import  java.io.*; //primitive type이 아닌 object를 파일에 읽고 쓰는 예제 • public class TestSerialization implements Serializable { •          String name; •           int age = 7; •          TestSerialization (String name, int age) { •                       this.name = name; •                       this.age = age; •       } • } public class SerializeMyObject { //TestSerialization class의 object를 파일에 write예제 TestSerialization ts;               public static void main(String [] args) throws Exception {                           SerializeMyObject smo = new SerializeMyObject();                           smo.writeMyObject(); // object를 file로 write함.                           smo.ts = null; // object를 memory에서 없앰.                           smo.readMyObject(); // 파일에서 object를 다시 읽어옴.                           System.out.println(smo.ts.name);               }

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

More Related