본문 바로가기

Java

Java(19) - 입출력, 스트림, 보조 스트림, 직렬화, 파일 관리

728x90
반응형

1) 입출력

   1-1) 스트림(이진 스트림, 문자 스트림, 문자 인코딩)

   1-2) 보조 스트림(버퍼 입출력, 파일 복사)

   1-3) 직렬화

   1-4) 파일 관리(File class)

 

 

 

 

1) 입출력

1-1) 스트림(이진 스트림, 문자 스트림, 문자 인코딩)

패키지 chapter16.ioStream

IoStream_out.class

package chapter16.ioStream;

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

public class IoStream_out {

	public static void main(String[] args) {
		byte[] data = {8, 9, 0, 6, 2, 9, 9};
		FileOutputStream out = null;
		
		try {
			out = new FileOutputStream("test.txt");
			out.write(data);
			System.out.println("Write success");
		} catch (IOException e) {
			System.out.println("File output error");
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}

 

 

 

IoStream_in1.class

package chapter16.ioStream;

import java.io.FileInputStream;

public class IoStream_in1 {

	public static void main(String[] args) throws Exception {
		FileInputStream in = new FileInputStream("test.txt");
		int avail = in.available();   // 스트림에서 읽을 수 있는 byte 개수 리턴
		System.out.println(avail);
		
		byte[] data = new byte[avail];
		in.read(data);   // 지정된 배열 크기만큼 읽고 버퍼배열에 저장, 읽은 개수 리턴
		in.close();   // 스트림 닫고 자원 해제
		for (byte b : data) {
			System.out.print(b);
		}
		

	}

}

 

 

 

IoStream_in2.class

package chapter16.ioStream;

import java.io.FileInputStream;

public class IoStream_in2 {

	public static void main(String[] args) throws Exception {
		FileInputStream in = new FileInputStream("test.txt");
		int data;
		for (;;) {
			data = in.read();
			if (data == -1) {  // "read()" 메서드의 경우, 더이상 뽑아올 데이터가 없는 경우 "-1"을 반환한!
				break;
			}
			System.out.print(data);
		}
		in.close();

	}

}

 

 

 

IoStream_letter.class

package chapter16.ioStream;

import java.io.FileReader;
import java.io.FileWriter;

public class IoStream_letter {

	public static void main(String[] args) throws Exception {
		String str = "자바 Stream 입출력";
		FileWriter out = new FileWriter("test.txt");
		out.write(str);
		out.close();
		System.out.println("write success");
		
		// 한 문자씩 읽기
		FileReader in = new FileReader("test.txt");
		int ch;
		for (;;) {
			ch = in.read();
			if (ch == -1) {
				break;
			}
			System.out.print((char) ch);
		}
		in.close();
		System.out.println();
		
		// 한꺼번에 읽기
		in = new FileReader("test.txt");
		char[] text = new char[100];
		int num = in.read(text);
		System.out.println("읽은 문자 개수 = " + num);
		System.out.println(text);
		in.close();

	}

}

 

 

 

IoStream_encoding.class

package chapter16.ioStream;

import java.io.FileReader;

public class IoStream_encoding {

	// 문자를 byte로 바꿔주는 것을 "encoding"이라고 하며, 반대로 byte를 문자로 바꿔주는 것을 "decoding"이라 함!
	public static void main(String[] args) throws Exception {
		// FileReader in = new FileReader("애국가.txt");
		// FileReader in = new FileReader("애국가-Unicode.txt");
		// FileReader in = new FileReader("애국가-Utf8.txt");
		FileReader in = new FileReader("애국가-Utf8nb.txt");
		
		char[] text = new char[100];
		int num = in.read(text);
		System.out.println("읽은 문자 개수 = " + num);
		System.out.println(text);
		in.close();

	}

}

 

 

 

IoStream_encoding2.class

package chapter16.ioStream;

import java.io.FileInputStream;
import java.io.InputStreamReader;

public class IoStream_encoding2 {

	public static void main(String[] args) throws Exception {
		FileInputStream fi = new FileInputStream("애국가.txt");
		InputStreamReader in = new InputStreamReader(fi, "euc-kr");
		char[] text = new char[100];
		int num = in.read(text);
		System.out.println(text);
		in.close();

	}

}

 

 

 

 

1-2) 보조 스트림(버퍼 입출력, 파일 복사)

Buffered_Test.class

package chapter16.ioStream;

import java.io.BufferedReader;
import java.io.FileReader;

public class Buffered_Test {

	public static void main(String[] args) throws Exception {
		BufferedReader in = new BufferedReader(new FileReader("애국가-Utf8nb.txt"));
		/*
		char[] text = new char[100];
		int num = in.read(text);
		System.out.println("읽은 문자 개수 = " + num);
		System.out.println(text);
		in.close();
		*/
		
		int data;
		for (;;) {
			data = in.read();
			if (data == -1) {
				break;
			}
			System.out.print((char) data);
		}
		in.close();

	}

}

 

 

 

IoStream_filecopy.class

package chapter16.ioStream;

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

public class IoStream_filecopy {

	public static void main(String[] args) throws Exception {
		long start = System.currentTimeMillis();
		System.out.println("복사 시작");
		
		FileInputStream src = new FileInputStream("애국가-Utf8nb.txt");
		FileOutputStream dest = new FileOutputStream("test2.txt");
		// BufferedInputStream src = new BufferedInputStream(new FileInputStream("애국가-Utf8nb.txt"));
		// BufferedOutputStream dest = new BufferedOutputStream(new FileOutputStream("test2.txt"));
		
		int data;
		for (;;) {
			data = src.read();
			if(data == -1) {
				break;
			}
			dest.write(data);
		}
		src.close();
		dest.close();
		System.out.println("복사 완료");
		System.out.println(System.currentTimeMillis() - start / 1000.0 + "초 걸림");

	}

}

 

 

 

 

1-3) 직렬화

Serialization.class

package chapter16.ioStream;

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

class Person implements Serializable {   // 직렬화를 하겠다는 의도를 표시
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;    // SUID
	String name;
	// transient 키워드 : 해당 변수를 직렬화 대상에서 제외함
	transient String job;   // 직렬화 대상 제외(해당 변수가 가지고 있는 값이 보안 상 민감한 정보에 해당되면 해당 변수 값을 출력하지 않도록 처리하는 것을 의미함)
	
	public Person() {}
	public Person(String name, String job) {
		this.name = name;
		this.job = job;
	}
	
	@Override
	public String toString() {
		return name + ", " + job;
	}
}

public class Serialization {

	public static void main(String[] args) throws ClassNotFoundException {
		Person personAhn = new Person("안재용", "대표이사");
		Person personKim = new Person("김철수", "상무이사");
		
		// 직렬화
		try (FileOutputStream fos = new FileOutputStream("serial.out");
				ObjectOutputStream oos = new ObjectOutputStream(fos)) {
			oos.writeObject(personAhn);
			oos.writeObject(personKim);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// 역직렬화
		try (FileInputStream fis = new FileInputStream("serial.out");
				ObjectInputStream ois = new ObjectInputStream(fis)) {
			Person p1 = (Person) ois.readObject();
			Person p2 = (Person) ois.readObject();
			System.out.println(p1);
			System.out.println(p2);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

 

 

 

 

1-4) 파일 관리(File class)

File_Info.class

package chapter16.ioStream;

import java.io.File;

public class File_Info {

	public static void main(String[] args) {
		File f = new File("C://TestFolder//fileTest.txt");
		if (f.exists()) {   // 파일 존재 여부
			if (f.isFile()) {   // 경로가 파일인지 검사
				System.out.println("파일입니다.");
				System.out.println("파일 경로: " + f.getParent());
				System.out.println("파일 경로2: " + f.getPath());
				System.out.println("파일 이름: " + f.getName());
				System.out.println("파일 크기: " + f.length());
				System.out.println("숨김 파일: " + f.isHidden());
				System.out.println("절대 경로: " + f.isAbsolute());
			} else if (f.isDirectory()) {   // 경로가 디렉터리인지 검사
				System.out.println("디렉터리입니다.");
			}
		} else {
			System.out.println("파일이 없습니다.");
		}

	}

}

 

 

 

File_makedir.class

package chapter16.ioStream;

import java.io.File;
import java.io.FileWriter;

public class File_makedir {

	public static void main(String[] args) throws Exception {
		File folder = new File("C://TestFolder");
		
		if (folder.mkdir()) {   // 새로운 디렉터리를 생성
			File file = new File("C://TestFolder//MyFile.txt");
			if (file.createNewFile()) {   // 새로운 파일을 생성
				FileWriter out = new FileWriter(file);
				out.write("테스트 입니다 123");
				out.close();
			}
		}

	}

}