KIC/JAVA

day34 - JAVA (자바, IO스트림)

바차 2021. 7. 30. 12:06
반응형

 

[FileOutputStream 예제]

package javaPro.java_io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Date;

public class FileOutputStreamEx2 {
    public static void main(String[] args) {
        firstMethod();
    }

    private static void firstMethod() {
        secondMethod();
    }

    private static void secondMethod() {
        try {
            throw new Exception("파일에 예외 메시지 저장");
        } catch (Exception e) {
            e.printStackTrace();
            try {
                /*
                 * ("error.log",true) "error.log" : 생성할 파일의 이름. 파일 없으면 생성. 파일이 있으면 내용 변경
                 * true/false : true : 파일이 있는 경우 기존의 내용에 새로운 내용을 추가 false :파일이 있는 경우 기존의 내용을 새로운
                 * 내용으로 변경
                 */

                FileOutputStream fos = new FileOutputStream("error.log", true);
                fos.write(("1: " + e.getMessage()).getBytes());
                // error.log 파일에 e.printStackTrace() 내용을 출력
                fos.write(("1:" + e.getMessage() + "\n\n").getBytes());
                fos.write(("2.====================\n\n" + (new Date()) + "\n\n").getBytes());
                e.printStackTrace(new PrintStream(fos));
                fos.write("3.====================\n\n".getBytes());
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
    }
}

 

 

[PrintStream 예제]

package javaPro.java_io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class PrintStreamEx1 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("Print.txt");
        PrintStream ps = new PrintStream(fos, true);
        // true : autoflush 기능 추가

        ps.println("홍길동");
        ps.println(1234);
        ps.println(true);
        ps.println(65);
        ps.println(65);

        ps.flush();
        ps = new PrintStream("print2.txt");
        ps.println("홍길동");
        ps.println(1234);
        ps.println(true);
        ps.println(65);
        ps.println(65);

        ps.flush();

    }

}

 

 

 

 

[Object의 output, input 예제]

[output]

package javaPro.java_io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/*
 * ObjectOutputStream 예제
 * - 객체를 외부로 전송하는 스트림.
 * - 전송되는 객체는 반드시 Serializable 인터페이스를 구현해야 한다.
 *    java.io.NotSerializableException : 직렬화 대상 객체가 아님 
 * - 객체를 외부로 전송하는 기능을 직렬화라 한다.
 * - ObjectInputStream 을 이용하여 객체를 받을 수 있다.
 */

class Customer implements Serializable { // 외부에 객체를 전송/저장 할 때는 Serializable해줘야 한다.
    private String name;

    // transient : age 변수값은 직렬화 대상에서 제외시킨다.
    private transient int age;
    // private int age;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "[" + " name=" + name + ", age=" + age + "]";
    }

}

public class ObjectOutputStreamEx1 {
    public static void main(String[] args) throws IOException { // 지금 이 throws IOException은 try 구문 가독성 떨어져 귀찮을때 사용
        FileOutputStream fos = new FileOutputStream("Object.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        Customer c1 = new Customer("홍길동", 20);
        Customer c2 = new Customer("김삿갓", 30);
        oos.writeObject(c1); // c1 객체를 외부로 출력
        oos.writeObject(c2);

        System.out.println("고객1 : " + c1);
        System.out.println("고객2 : " + c2);
    }
}

 

[input]

package javaPro.java_io;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ObjectInputStreamEx1 {

    // ObjectOutputStreamEx1 을 읽으려면 동일한 패키지 내에 있어야 한다.
    // Customer가 default로 선언 되어 있기 때문
    public static void main(String[] args) throws ClassNotFoundException, IOException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.ser"));
        Customer c1 = (Customer) ois.readObject();
        Customer c2 = (Customer) ois.readObject();

        System.out.println("고객1" + c1);
        System.out.println("고객2" + c2);

        // age를 ObjectOutputStreamEx1에서 transient해놨다면 값이 저장되지 않는다.
        // transient을 해제하면 age도 값이 저장된다.

    }
}

 

[결과 화면]

-> transient을 사용했다면 age에 값이 저장이 안된다.

300x250