ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Java - Stream IO
    Java 2018. 2. 2. 14:25
    반응형
    // 보조 스트림

    // 보통 1~2단계까지 보조를 거친다

    // 주가 보조로 합쳐지는 것



    import java.io.FileInputStream;

    import java.io.FileOutputStream;

    import java.io.InputStreamReader;

    import java.io.OutputStreamWriter;



    public class TextFileCopy {



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

            

            // 1. 파일 위치

            String oriPath = "D:/news.txt";

            String targetPath = "D:/newsCopy.txt";

            // 2. 스트림

            FileInputStream fis = new FileInputStream(oriPath);

            FileOutputStream fos = new FileOutputStream(targetPath);

            // 2-1 보조 스트림 준비

            InputStreamReader reader = new InputStreamReader(fis, "UTF-8");

            OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");

            

            // 3. 읽고 쓰기

    //      int data; // stream 방식

    //      while((data = fis.read()) != -1) {

    //          fos.write((char)data);

    //      }

            

            // 보조 스트림 읽고 쓰기

            char[] cArr = new char[1024];

            while(reader.read(cArr) != -1) {

                writer.write(cArr);

            }

            

            // 4. 반납

            writer.flush(); // 보조 writer 자원 비우기

            // 주랑 마찬가지로 보조도 자원 반납

            fos.close();

            reader.close();

            fis.close();

            writer.close();

        }



    }





    // Buffered Reader/Writer

    public class TimeChecker {
        
        long start;
        long end;
        
        public void timeStart() {
            start = System.currentTimeMillis();
        }
        
        public long timeStop() {
            end = System.currentTimeMillis();
            return end-start;
        }

    }


    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.InputStream;

    public class BufferNotUse extends TimeChecker {

        public static void main(String[] args) throws Exception {
            
            // 1. 경로
            String oriPath = "D:/bang.gif";
            String targetPath = "D:/bangCopy.gif";
            // 2. 스트림
            FileInputStream fis = new FileInputStream(oriPath);
            FileOutputStream fos = new FileOutputStream(targetPath);
            TimeChecker tch = new TimeChecker(); // 시간 체크 객체
            // 3. 읽고
            tch.timeStart();
            byte[] b= new byte[1024];
            while(fis.read() != -1) {
                fos.write(b); // 4. 쓰고
            }
            System.out.println("걸린 시간 : "+Math.abs(tch.timeStop()/1000)+"초");
            // 5. 반납
            fos.flush();
            fos.close();
            fis.close();
            
        }

    }



    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;

    public class BufferUse extends TimeChecker {

        public static void main(String[] args) throws Exception {
            
            // 1. 경로
            String oriPath = "D:/bang.gif";
            String targetPath = "D:/bangCopy.gif";
            // 2. 스트림
            FileInputStream fis = new FileInputStream(oriPath);
            FileOutputStream fos = new FileOutputStream(targetPath);
            // Buffered Stream
            BufferedInputStream bis = new BufferedInputStream(fis);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            
            TimeChecker tch = new TimeChecker(); // 시간 체크 객체
            // 3. 읽고
            tch.timeStart();
            byte[] b= new byte[1024];
            while(bis.read(b) != -1) {
                bos.write(b); // 4. 쓰고
            }
            
    //      int data;
    //      while((data = bis.read()) != -1) {
    //          bos.write(data);
    //      }
            System.out.println("걸린 시간 : "+Math.abs(tch.timeStop()/1000)+"초");
            // 5. 반납
            bos.flush();
            fos.close();
            bos.close();
            fis.close();
            bis.close();

        }

    }






    < Data I/O >
    // .dat 읽어 오기

    import java.io.DataOutputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;

    public class DataOut {

        public static void main(String[] args) throws Exception {
            
            // 1. 위치
            String path = "D:/data.dat";
            // 2. 스트림
            FileOutputStream fos = new FileOutputStream(path);
            DataOutputStream dos = new DataOutputStream(fos);
            // 3. 쓰기
            dos.writeUTF("상무");
            dos.writeBoolean(true);
            dos.writeInt(275);
            // 4. 반납
            dos.flush();
            dos.close();
    fos.close();
            
        }

    }







    < Obj I/O >



    import java.io.Serializable;
    // Serializable을 구현 받지 않으면 파일 전송이 불가능 하다.
    public class Sample implements Serializable{
        int num = 11;
        String team = "Sangmoo Team";
        String job = "Programmer";
        
        public String method() {
            return "불렀습니까?";
        }
        
    }



    import java.io.FileOutputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.util.HashMap;

    public class ObjOut {

        public static void main(String[] args) throws Exception {
            
            // 1. 위치
            String path = "D:/io/obj.dat";
            // 2. 스트림
            FileOutputStream fos = new FileOutputStream(path);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            // HashMap
            HashMap<String, String> map = new HashMap<>();
            map.put("name", "Sangmoo");
            map.put("phone", "01089416248");
            oos.writeObject(map);
            // Array
            int[] arr = {85, 90, 80, 95, 75};
            oos.writeObject(arr);
            // UTF
            oos.writeUTF("기본 문자열도 받을 수 있다.");
            // Instance -> 객체 직렬화 해야함 implements Serializable
            oos.writeObject(new Sample());
            // 3. 내보내기
            // 4. 반납
            oos.flush();
            oos.close();
            fos.close();
            
        }

    }




    import java.io.FileInputStream;
    import java.io.ObjectInputStream;
    import java.util.HashMap;

    public class ObjIn {

        public static void main(String[] args) throws Exception {
            
            // 1. 위치
            String path = "D:/io/obj.dat";
            // 2. 스트림
            FileInputStream fis = new FileInputStream(path);
            ObjectInputStream ois = new ObjectInputStream(fis);
            // 3. 읽고 쓰기
            HashMap<String, String> map = (HashMap<String, String>) ois.readObject();
            int[] arr = (int[]) ois.readObject();
            String msg = ois.readUTF();
            Sample sample = (Sample) ois.readObject();
            
            System.out.println("name : "+map.get("name"));
            System.out.println("phone : "+map.get("phone"));
            for(int a : arr) {
                System.out.println("arr[] : "+a);
            }
            System.out.println(msg);
            System.out.println(sample.method());
            // 4. 반납
            fis.close();
            ois.close();
            
        }

    }




    < Properties I/O >

    // Properties는 Map과 비슷하다.
    // put으로 Key, Value값을 넣는다.
    // store는 Key, Comment 형식으로 되어 있다
    // 값을 넣을 땐 put, 파일을 쓸때는 store을 쓴다.
    // Comment는 맨위에 작성되고, 바로 밑에는 날짜가 적힌다.


    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.util.Properties;

    public class PropWrite {

        public static void main(String[] args) throws Exception {
            
            // properties 객체화
            Properties prop = new Properties();
            // properties에 값 넣기
            prop.put("id", "cossack7");
            prop.put("pw", "275");
            prop.put("name", "Sangmoo");
            prop.put("email", "first_1st@naver.com");
            prop.put("phone", "010-8941-6248");
            
            // 위치
            String path = "C:/Users/user1/git/Kh_Java_Programming/Java_Programming/Chapter11/chap11/exam13/prop/profile.properties";
            // 스트림
            FileOutputStream fos = new FileOutputStream(path);
            // 파일쓰기
            prop.store(fos, "Sangmoo Profile");
            System.out.println("저장 완료");
            // 반납
            fos.flush();
            fos.close();

        }

    }





    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.util.Properties;

    public class PropRead {

        public static void main(String[] args) throws Exception {
            
            // 1. 불러올 파일 지정
            String path = "C:/Users/user1/git/Kh_Java_Programming/Java_Programming/Chapter11/chap11/exam13/prop/profile.properties";
            // 2. 스트림 준비
            FileInputStream fis = new FileInputStream(path);
            // 3. 읽어오기
            // Properties 형식으로 읽어와야 한다.
            Properties prop = new Properties();
            prop.load(fis);
            System.out.println("id : "+prop.getProperty("id"));
            System.out.println("pw : "+prop.getProperty("pw"));
            System.out.println("name : "+prop.getProperty("name"));
            System.out.println("email : "+prop.getProperty("email"));
            System.out.println("phone : "+prop.getProperty("phone"));
            // 4. 반납
            fis.close();

    // get()으로 가져오면 Object형식
    // getProperty()로 가져오면 String형식이다.
    // properties가 String형식이기 때문에 둘다 써도 된다.

    * // Ctrl + Shift + O 를 통해서 사용하지 않는 import를 없앨 수 있다.
            
        }

    }







    반응형

    'Java' 카테고리의 다른 글

    Java - Network - Chat  (0) 2018.02.06
    Java - Network  (0) 2018.02.05
    Java - File I/O  (0) 2018.02.01
    Java - Java I/O  (0) 2018.02.01
    Mac에서 이클립스로 C언어 프로그래밍하기  (0) 2018.02.01

    댓글

Designed by Tistory.