[JAVA_Back-End]

[JAVA] Data/객체 입출력 본문

Programming/JAVA

[JAVA] Data/객체 입출력

너굴위 2023. 9. 1. 12:14
728x90
반응형

< 지난시간 포스팅 정리 >

 

[JAVA] 파일 입출력

< 지난 포스팅 정리 > [JAVA] 컬렉션 프레임웍 - HashMap < 지난 포스팅 정리 > [JAVA] 에러처리 + ArrayList < 지난시간 정리 > 객체지향 프로그램 특성 캡슐화 - 외부로부터 직접 멤버필드에 접근 금지(Data h

thstnqls.tistory.com

java.io

데이터 입력출력 - 문자열 입력 

                           - 자료형을 유지하면 입출력

=> 2차 스트림을 사용

DataInputStream / DataOutputStream


* DataInputStreamEx01.java - 각자 다른 데이터 저장하기
public class DataInputStreamEx01 {


public static void main(String[] args) {

DataInputStream dis = null;

try {
dis = new DataInputStream(new FileInputStream("./data.dat"));
System.out.println(dis.readInt());
System.out.println(dis.readUTF());
System.out.println(dis.readFloat());
} catch (FileNotFoundException e) {
System.out.printf("[에러]: ",e.getMessage());
} catch (IOException e) {
System.out.printf("[에러]: ",e.getMessage());
}finally {
if(dis!=null)try {dis.close();}catch(IOException e) {};
}
}
}

 

* DataOutputStreamEx01.java - 저장한 데이터 출력하기
public class DataOutputStreamEx01 {


public static void main(String[] args) {
// TODO Auto-generated method stub


//자료형을 유지하면서 입출력

DataOutputStream dos = null;

try {

//binary
dos = new DataOutputStream(new FileOutputStream("./data.dat"));

dos.writeInt(2023);
dos.writeUTF("한글 저장");
dos.writeFloat(1.8f);

System.out.println("저장완료");
} catch (FileNotFoundException e) {
System.out.printf("[에러]: ",e.getMessage());
} catch (IOException e) {
System.out.printf("[에러]: ",e.getMessage());
}finally {
if(dos!=null)try {dos.close();}catch(IOException e) {};
}
}
}

 

try~catch~finally 계속적으로 이 구조를 작성하는 데에는 한계가 있음

try ~ with ~ resource ~ catch ~

try(익셉션 발생 문장) ~ catch ~  로 작성

* ExceptionEx01 - try ~ catch문 finally없이 사용하기
public class ExceptionEx01 {


public static void main(String[] args) {

//try ~ with ~ resource
//제일 가독성 좋다고 생각함
try(FileInputStream fis = new FileInputStream("./data.txt")){ //따로 close를 시켜주지 않아도 try에서 알아서 close가 된다.
int data =0;
while((data=fis.read())!= -1) {
System.out.print((char)data);
}
}catch(IOException e) {
System.out.printf("[에러]: ",e.getMessage());
}
}
}

 

* SystemInEx01 - Scanner을 통해 입력값 받기
public class SystemInEx01 {


public static void main(String[] args) {
// TODO Auto-generated method stub


//Scanner sc = new Scanner(System.in);
//io는 항상 finally로 close하기

InputStream is = null;

try {
is=System.in;
System.out.println("입력:");
System.out.println("입력값: "+(char)is.read()); //문자를 여러 개 받고싶을 때
System.out.println("입력값: "+(char)is.read());
System.out.println("입력값: "+(char)is.read());

} catch (IOException e) {
System.out.printf("[에러]: ",e.getMessage());
}finally {
if(is!=null)try {is.close();}catch(IOException e) {};
}
}
}

 

* SystemInEx02- BufferedReader + readLine으로 버퍼입력값 한줄에 받기
public class SystemInEx02 {


public static void main(String[] args) {

BufferedReader br=null; //한글 깨짐현상 없앨 수 있도록 바이트기반 스트림을 문자기반 스트림으로 변경할 수 있도록 하는 InputStreamReader을 사용한다.
//또한 가속화시키기 위해 BufferedReader을 사용한다.
try {
br=new BufferedReader( new InputStreamReader(System.in));

System.out.println("입력:");

System.out.println("입력값: "+br.readLine());


} catch (IOException e) {
System.out.printf("[에러]: ",e.getMessage());
}finally {
if(br!=null)try {br.close();}catch(IOException e) {};
}
}

}

 

* SystemInEx03 - BufferedReader을 이용한 구구산 연산기
public class SystemInEx03 {


public static void main(String[] args) {



BufferedReader br=null;
try {
br=new BufferedReader( new InputStreamReader(System.in));

System.out.println("입력:");
String num=br.readLine();
for(int i=1;i<=9;i++) {
System.out.println(num+"x"+i+"="+Integer.parseInt(num)*i);
}

} catch (IOException e) {
System.out.printf("[에러]: ",e.getMessage());
}finally {
if(br!=null)try {br.close();}catch(IOException e) {};
}
}
}

 

* Ex15_20 - 객체로 값 작성 후 ArrayList에 넣기 => ObjectOutputStream사용하여 입력
public class Ex15_20 {


public static void main(String[] args) {
try {
String fileName ="UserInfo.ser";
FileOutputStream fos = new FileOutputStream(fileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream out = new ObjectOutputStream(bos);


UserInfo u1 = new UserInfo("JavaMan","1234",30);
UserInfo u2 = new UserInfo("Javaman","4321",26);

ArrayList<UserInfo> list = new ArrayList<>();
list.add(u1);
list.add(u2);

out.writeObject(u1);
out.writeObject(u2);
out.writeObject(list);
out.close();
System.out.println("직렬화가 잘 끝났습니다.");
}catch(IOException e) {
e.printStackTrace();
}
}
}
* Ex15_21 - 작성한 ArrayList를 ObjectInputStream사용하여 출력 
public class Ex15_21 {
public static void main(String[] args) {
try {
String fileName ="Userinfo.ser";
FileInputStream fis = new FileInputStream(fileName);
BufferedInputStream bis = new BufferedInputStream(fis);


ObjectInputStream in = new ObjectInputStream(bis);


UserInfo u1 = (UserInfo)in.readObject();
UserInfo u2 = (UserInfo)in.readObject();
ArrayList list =(ArrayList)in.readObject();


System.out.println(u1);
System.out.println(u2);
System.out.println(list);
in.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}

* UserInfo - 객체 Class
public class UserInfo implements Serializable {       //implements Serializable을하면  객체의 직렬화 된다.
String name;
String password;
int age;


public UserInfo() {
this("Unknown","1111",0);
}

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

public String toString() {
return "("+name+","+password+","+age+")";
}
}

person  p1  p2  p3

만든 후 ArrayList로 집어넣고 해당 ArrayList를 file에 넣기 

 

* ObjectOutputStreamEx01.java - 객체 데이터 직렬화
public class ObjectOutputStreamEx01 {


public static void main(String[] args) {

//직렬화 : 객체를 데이터 스트림으로 만드는 것.
// 객체에 저장된 데이터를 스트림에 쓰기 위해 연속적인 데이터로 변환하는 것
ObjectOutputStream oos = null;

try {
oos = new ObjectOutputStream(new FileOutputStream("./object.dat"));


//다양한 객체를 넣을 수 있다.
String[] names = {"홍길동","손수빈","정민우"}; //객체 데이터 생성
int[] ages= {104,23,24};
double[] weight= {12,53.2,60.3};

oos.writeObject(names); // 객체 데이터 저장
oos.writeObject(ages);
oos.writeObject(weight);

System.out.println("저장완료");
} catch (FileNotFoundException e) {
System.out.printf("[에러]: ",e.getMessage());
} catch (IOException e) {
System.out.printf("[에러]: ",e.getMessage());
}finally {
if(oos!=null)try {oos.close();}catch(IOException e) {};
}
}
}

 

* ObjectInputStreamEx01 - 직렬화 한 객체 데이터 역직렬화를 통해 출력
public class ObjectInputStreamEx01 {


public static void main(String[] args) {
// 역직렬화: 스트림으로부터 데이터를 읽어서 객체를 만드는 것
//역직렬화 시 반환타입이 Object이기 때문에 객체 원래의 타입으로 형변환 해주어야 한다.

ObjectInputStream ois = null;

try {
ois = new ObjectInputStream(new FileInputStream("./object.dat"));

String[] names = (String[])ois.readObject(); //객체를 읽어온다. 반환타입은 Object이기 때문에 원래 타입으로 형변환 해준다.
int[] ages = (int[])ois.readObject();
double[] weights=(double[])ois.readObject();

System.out.println(Arrays.toString(names)); //배열의 형태로 출력한다
System.out.println(Arrays.toString(ages));
System.out.println(Arrays.toString(weights));

} catch (FileNotFoundException e) {
System.out.printf("[에러]: ",e.getMessage());
} catch (ClassNotFoundException e) {
System.out.printf("[에러]: ",e.getMessage());
} catch (IOException e) {
System.out.printf("[에러]: ",e.getMessage());
}finally {
if(ois!=null)try {ois.close();}catch(IOException e) {};
}
}
}

 

* ObjectOutputStreamEx02.java - 객체를 따로 만들어 데이터 저장 후 ObjectOutputStream으로 serial.dat파일에 입력하기
public class ObjectOutputStreamEx02 {


public static void main(String[] args) {

ObjectOutputStream oos = null;

try {
oos = new ObjectOutputStream(new FileOutputStream("./serial.dat"));


Person p = new Person("홍길동","010-1111-1111",20,"서울시");

oos.writeObject(p); // 따로 만든 객체에 데이터 저장


System.out.println("저장완료");
} catch (FileNotFoundException e) {
System.out.printf("[에러]: ",e.getMessage());
} catch (IOException e) {
System.out.printf("[에러]: ",e.getMessage());
e.printStackTrace();
}finally {
if(oos!=null)try {oos.close();}catch(IOException e) {};
}
}
}
* Person.java  - ObjectOutputStream을 통해 파일에 넣을 객체 생성하기
import java.io.Serializable;
// 따로 만든 클래스를 ObjectOutputStream으로 적용하고 싶을 때
//[에러]: java.io.NotSerializableException: Person
//at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1187)
//at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:350)
//at ObjectOutputStreamEx02.main(ObjectOutputStreamEx02.java:18)
//객체가 직렬화 되지 않았다는 에러가 발생한다 따라서 알아서 직렬화를 시킬 수 있도록 implements Serializable을 추가한다.


public class Person implements Serializable {
private String name;
private String phone;
private int age;
transient String address; //transient: 민감한 정보를 직렬화대상에서 제외시킬 수 있음


public Person(String name, String phone, int age, String address) {
this.name = name;
this.phone = phone;
this.age = age;
this.address = address;
}

public String getName() {
return name;
}

public String getPhone() {
return phone;
}

public int getAge() {
return age;
}

public String getAddress() {
return address;
}

}

 

* ObjectInputStreamEx02.java - 파일에 넣은 데이터를 불러오기
public class ObjectInputStreamEx02 {


public static void main(String[] args) {
// 역직렬화: 스트림으로부터 데이터를 읽어서 객체를 만드는 것
//역직렬화 시 반환타입이 Object이기 때문에 객체 원래의 타입으로 형변환 해주어야 한다.

ObjectInputStream ois = null;

try {
ois = new ObjectInputStream(new FileInputStream("./serial.dat"));

Person p = (Person)ois.readObject(); //파일에 넣은 데이터를 불러온다

System.out.println(p.getName());
System.out.println(p.getPhone());
System.out.println(p.getAge());
System.out.println(p.getAddress()); //address를 transient로 설정해놨기 때문에 null로 뜬다


} catch (FileNotFoundException e) {
System.out.printf("[에러]: ",e.getMessage());
} catch (ClassNotFoundException e) {
System.out.printf("[에러]: ",e.getMessage());
} catch (IOException e) {
System.out.printf("[에러]: ",e.getMessage());
}finally {
if(ois!=null)try {ois.close();}catch(IOException e) {};
}
}
}

 

* ObjectOutputStreamEx03.java - 객체와 ArrayList를 사용하여 파일에 값 저장하기
public class ObjectOutputStreamEx03 {


public static void main(String[] args) {




ObjectOutputStream oos = null;

try {
oos = new ObjectOutputStream(new BufferedOutputStream( new FileOutputStream("./serial2.dat")));
Person p1 = new Person("홍길동","010-1111-1111",20,"서울시");
Person p2 = new Person("손수빈","010-2222-2222",23,"수원시");
Person p3 = new Person("정민우","010-3333-3333",24,"시흥시");

ArrayList<Person> person= new ArrayList<>();

person.add(p1);
person.add(p2);
person.add(p3);

oos.writeObject(p1);
oos.writeObject(p2);
oos.writeObject(p3);


System.out.println("저장완료");
} catch (FileNotFoundException e) {
System.out.printf("[에러]: ",e.getMessage());
} catch (IOException e) {
System.out.printf("[에러]: ",e.getMessage());
}finally {
if(oos!=null)try {oos.close();}catch(IOException e) {};
}
}


}

 

* ObjectInputStreamEx03 - 역직렬화를 통해 ArrayList에 저장한 값 출력하기 (미완성)- 애매함
public class ObjectInputStreamEx03 {


public static void main(String[] args) {
// 역직렬화: 스트림으로부터 데이터를 읽어서 객체를 만드는 것
//역직렬화 시 반환타입이 Object이기 때문에 객체 원래의 타입으로 형변환 해주어야 한다.

ObjectInputStream ois = null;

try {
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("./serial2.dat")) );

Person p1=(Person)ois.readObject();
Person p2=(Person)ois.readObject();
Person p3=(Person)ois.readObject();


System.out.println(p1);
System.out.println(p2);
System.out.println(p3);


/*System.out.println(p1.getName());
System.out.println(p1.getPhone());
System.out.println(p1.getAge());
System.out.println(p1.getAddress());

System.out.println(p2.getName());
System.out.println(p2.getPhone());
System.out.println(p2.getAge());
System.out.println(p2.getAddress());


System.out.println(p3.getName());
System.out.println(p3.getPhone());
System.out.println(p3.getAge());
System.out.println(p3.getAddress());

*/
} catch (FileNotFoundException e) {
System.out.printf("[에러]: ",e.getMessage());
} catch (ClassNotFoundException e) {
System.out.printf("[에러]: ",e.getMessage());
} catch (IOException e) {
System.out.printf("[에러]: ",e.getMessage());
}finally {
if(ois!=null)try {ois.close();}catch(IOException e) {};
}


}


}
//결과적으로 객체의 값이 나오는 것이 아닌 객체의 주소값이 나오게 되어 아직 해결 못한 상태임

 


  • DB설치하기

C:\Program Files\MariaDB 11.1\   - DB설치경로

 

root계정 비밀번호 설정

 

3306포트로 설정

 

< 서버 프로그램 >

서비스 -> mariadb확인 -> window 켜지면 자동으로 돌아가도록 설정되어있음.

 


- 다음주부터는 DB관련 내용 들어감 

- JAVA계속 복습하면서 까먹지 말도록 하기

- 오늘 시험 본 내용 중 getter setter부분 틀린 거 확인하기

728x90
반응형

'Programming > JAVA' 카테고리의 다른 글

[JAVA] GUI(2)  (0) 2023.09.12
[JAVA] 멀티스레드 + GUI(1)  (0) 2023.09.12
[JAVA] 파일 입출력  (0) 2023.08.31
[JAVA] 컬렉션 프레임웍 - HashMap  (0) 2023.08.30
[JAVA] 에러처리 + ArrayList  (0) 2023.08.29