본문 바로가기
Language/Java

[자바 기본 개념] Stream/ 예제

by 나비와꽃기린 2016. 6. 22.
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

2. Stream

2.1 바이트 스트림 클래스

- 바이트 단위의 바이너리 값을 읽고 쓰는 스트림

àInputStream/OutputStream/FileInputStream/FileOutputStream/DataInputStream/DataOutputStream

****예제1

public class _08FileInputStreamEx {

             public static void main(String[] args) {

                           // TODO Auto-generated method stub

                           FileReader in =null;

                           try {

                           //해당 소스 우클릭 Copy qualified name 누르면 됨

                           //in =new FileInputStream("src/day04/_07CollectionsEx.java");    //문자단위 읽어오지 못하는

                                        in =new FileReader("src/day04/_07CollectionsEx.java");          //문자단위도 읽어오는

                                        int c;

                                        while ((c=in.read())!=-1) { // 키보드에서 ctrl+z를 누르면 종료

                                                      System.out.print((char)c); //아스키코드값

                                        }

                                        in.close();

                           } catch (IOException e) {

                                        System.out.println("입출력오류");

                           }

             }

}

 

 

 

***예제2

public class _09FileOutputStremEx {

             public static void main(String[] args) {

                           try {

                                        //프로그램에 내용을 파일에 출력

                                        FileOutputStream fout=new FileOutputStream("src/day04/test.out");

                                        //입력용

                                        FileInputStream fin=null;

                                        //출력스트림에 저장 - 숫자 집어넣는 코드

                                        for (int i = 0; i < 10; i++) {

                                                      int n=10-i;

                                                      fout.write(n);

                                        }

                                        //메모리 반환

                                        fout.close();

                                        //파일에 저장되어있는 내용을 화면에 출력하는 소스

                                        fin=new FileInputStream("src/day04/test.out");

                                        int c=0;

                                        while ((c=fin.read())!=-1) {

                                                      System.out.print(c+" ");

                                        }

                                        fin.close();

                           } catch (Exception e) {

                                        // TODO: handle exception

                                        System.out.println("입출력 오류");

                           }  }

///test.out 저장은 바이트 단우로 저장되어있음

 

2.2 문자 스트림 클래스

- 유니 코드로 된 문자를 입출력 하는 스트림

àReader/Writer/InputStreamReader/OutputStreamWriter/FileReader/FileWriter

***예제1

public class _10FileWriterEx {

 public static void main(String[] args){

              InputStreamReader in= new InputStreamReader(System.in);

              FileWriter fout=null;

              int c;

              try {

                           fout=new FileWriter("src/day04/test01.out");

                           while ((c=in.read())!=-1) {   //파일의 끝이 아닐때까지 읽음

                                        fout.write(c);

                           }

                           in.close();

                           fout.close();

             } catch (Exception e) {

                           // TODO: handle exception

                           System.out.println("입출력오류");

             }

 }

}

 

***예제2

public class _11FileWriterEx {

             public static void main(String[] args) {

                            InputStreamReader in= new InputStreamReader(System.in);

                            BufferedOutputStream out= new BufferedOutputStream(System.out,5);

                            try {

                                         int c;

                                        while ((c=in.read())!=-1) {   //파일의 끝이 아닐때까지 읽음

                                                      out.write(c);  //버퍼가 다 창때 문자가 화면에 출력

                                        }

                                        out.flush();

                                        if(in!=null){

                                        in.close();

                                        out.close();

                                        }            

                           } catch (Exception e) {

                                        // TODO: handle exception

                                        System.out.println("입출력오류");

                           }

                          

             }

}

 

 

 

 

 

2.3 버퍼 입출력 스트림

-바이트 단위의 바이너리 데이터를 처리하는 버퍼 스트림à BufferedInputStream/BufferedOutputStream

-유니코드의 문자 데이터만 처리하는 버퍼 스트림à BufferedReader BufferedWriter

 

2.4 File 클래스

-파일의 경로명을 다루는 클래스

-파일 이름 변경, 삭제, 디렉터리 생성크기 등 파일 관리

***예제1

public class _12FileClassExample {

             public static void dir(File fd){

                           String[] filenames=fd.list();

                           for(String s:filenames){

                                        File f=new File(fd,s);

                                        long t=f.lastModified();

                                        System.out.println(s);

                                        System.out.println("파일크기:"+f.length());

                                        System.out.printf("수정한시간: %tb %td %ta %tT",t,t,t,t);

                           }

             }

             public static void main(String[] args) {

                           // TODO Auto-generated method stub

                           File f1=new File("src/day04/test.out");

                           File f2=new File("src/day04");

                           File f3=new File("src/");

                           String res;

                           if(f1.isFile())

                                        res="파일";

                           else

                                        res="디렉터리";

                           System.out.println(f1.getPath()+""+res+"입니다");

                           if(!f2.exists()){

                                        if(!f2.mkdir())

                                                      System.out.println("디렉터리생성실패");

                           }

                           if(f2.isFile())

                                        res="파일";

                           else

                                        res="디렉터리";

                           System.out.println(f2.getPath()+""+res+"입니다");

                           dir(f3);

                          

                           f2.renameTo(new File("/day04/src/day04/new_test.out"));

                           dir(f3);

             }

}

 

****예제2

public class _13TextCopy {

             public static void main(String[] args) {

                           // TODO Auto-generated method stub

                           File src= new File("src/day04/test.out"); //소스파일

                           File dst=new File("src/day04/test03.out"); //목적파일

                           FileReader fr=null;

                           FileWriter fw=null;

                           BufferedReader in=null;

                           BufferedWriter out=null;

                           int c;

                           try {

                                        fr=new FileReader(src);

                                        fw=new FileWriter(dst);

                                        in=new BufferedReader(fr);

                                        out=new BufferedWriter(fw);

                                        while ((c=in.read())!=-1) {

                                                      out.write((char)c);

                                        }

                                        in.close();

                                        out.close();

                                        fr.close();

                                        fw.close();

                           } catch ( IOException E) {

                                        // TODO: handle exception

                                        System.out.println("파일 복사 오류");

                           }

             }

}