상세 컨텐츠

본문 제목

[입출력스트림] 데이터스트림

자바

by esoesmio 2023. 4. 10. 21:09

본문

데이터형식으로 출력해냄

 

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class z26 {

    public static void main(String[] args) {

        try {
            DataOutputStream dos = new DataOutputStream( new FileOutputStream(  "/Users/eunsukkim/Desktop/car.txt"
            ));
            dos.writeUTF("현대");
            dos.writeUTF("아반떼");
            dos.writeDouble(450.5);
            dos.writeInt(6000);

            dos.writeUTF("현대");
            dos.writeUTF("소나타");
            dos.writeDouble(6150.5);
            dos.writeInt(1000);

            dos.writeUTF("현대");
            dos.writeUTF("바보");
            dos.writeDouble(9150.5);
            dos.writeInt(8000);

            dos.writeUTF("현대");
            dos.writeUTF("천재");
            dos.writeDouble(1250.5);
            dos.writeInt(100);

            dos.flush();
            dos.close();


            DataInputStream dis = new DataInputStream(new FileInputStream("/Users/eunsukkim/Desktop/car.txt"));
            List<car> carlist = new ArrayList<>();
            for(int i=0;i<3;i++){

                String company = dis.readUTF();
                String model = dis.readUTF();
                double maxspeed = dis.readDouble();
                int price = dis.readInt();

                car c = new car(company,model,maxspeed,price);
                carlist.add(c);


            }

            System.out.println(carlist);
dis.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());        }
    }


}
class car implements  Serializable{
    public static final long serialversionuid = 1;
//// 직렬화에서 제외하고 싶은 멤버변수는 타입 앞에 transient 키워드를 붙여준다.
private transient int produceYear;


    public car(String company, String model, double maxspeed, int price) {
        this.company = company;
        this.model = model;
        this.maxspeed = maxspeed;
        this.price = price;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public double getMaxspeed() {
        return maxspeed;
    }

    public void setMaxspeed(double maxspeed) {
        this.maxspeed = maxspeed;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    private String company;
    private String model;
    private double maxspeed;
    private int price;

    @Override
    public String toString() {
        return "car{" +
                "company='" + company + '\'' +
                ", model='" + model + '\'' +
                ", maxspeed=" + maxspeed +
                ", price=" + price +
                '}';
    }
}

관련글 더보기

댓글 영역