컴퓨터 관련/JAVA 강의

java #29 IO Stream -출력- (파일복사, 객체 JVM외부로 보내기/읽기)

승명 2016. 12. 18. 20:45

java #29 IO Stream -출력- (파일복사, 객체 JVM외부로 보내기/읽기)

 
- 관련 Post

* IO Stream 출력

- java.io package의 출력 Stream 관련 클래스들
- 8bit : 한글깨짐, 모든 파일 가능
- 16bit : 한글 깨지지 않으나 jpg 불가

bit

8bit Stream(byte 기반 Stram) = 한글 깨짐

16bit Stream(문자열 기반 Stream)

역할쓰기쓰기
상위 스트림OutputstreamWriter
스트림FileOutputStreamFileWriter
스트림ObjectOutputStreamBufferedWriter
스트림DataOutputStream



* 파일 생성

1. 8비트 (기본형 데이터 파일 생성 (문자열x))


- 객체화 및 사용법

1
2
3
4
5
① FileOutputStream fos = new FileOuntputStream(file경로) 
// 객체화, 입력된 file경로에 가서 파일이 없으면 생성하고 파일이 있으면 덮어쓴다.
② fos.write(정수); // 값을 스트림에 기록(파일이 아닌)
③ fos.flush(); // 스트림의 값을 목적지 파일로 분출
④ fos.close(); // 스트림 연결 끊기
cs


- 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void octalStream() {
          File file = new File("c:/dev/temp/octal.txt");
          try {
               // 목적지 파일에 쓰기 위하여 출력스트림 연결
               // 파일이 없으면 생성하고, 있으면 덮어 쓴다.          
               BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                         new FileOutputStream(file)));
 
               String msg = "오늘은 2014-03-10 월요일 신나는 월요병~";
               bw.write(msg); // 파일에 내모낼 내용을 스트림에 기록
               // bw.flush();// 스트림에 기록된 내뇽을 목적지 파일로 분출
               bw.close(); // 분출 후 연결을 끊어서 메모리 낭비를 막자
               System.out.println(file.getAbsolutePath() + "의 경로에 파일이 생성되었습니다.");
          } catch (FileNotFoundException e) {
               System.err.println("파일의 경로를 확인하세요");
               e.printStackTrace();
          } catch (IOException e) {
               System.out.println("출력 예외");
               e.printStackTrace();
          }// end catch
     }// oltalSream
 
cs


2. 8비트(문자열 파일 생성)


- 객체화
1
2
3
FileOutputStream fos = new FileOutputStream("경로");
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
cs
※ JVM->B.W->O.S.W->F.O.S->a.txt

- 사용법
1
2
3
bw.write(값); // 스트림에 데이터 쓰기
bw.flush(); // 스트림에 기록된 내용을 목적지 파일에 분출
bw.close(); // 연결 끊기
cs

- 예제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void hexStream() {
     // 파일의 정보설정
     File file = new File("c:/dev/temp/hex.txt");
     // 스트림 연결
     try {
          BufferedWriter bw = new BufferedWriter(new FileWriter(file));
          String data = "김덕수,윤충수,김병수";
          bw.write(data); // 값을 스트림에 쓰기
          bw.flush(); // 스트림의 내용을 목적지 파일로 분출
          bw.close(); // 분출이 완료되었으면 연결 끊기
          System.out.println("파일로 쓰기 완료");
     } catch (IOException e) {
          e.printStackTrace();
     }
}// helxStream
cs


3. 16비트(문자열 파일 생성)

 

 

- 객체화 및 사용법

1
2
3
4
5
FileWriter fw = new FileWriter(file); 
BufferedWriter bw = new BufferedWriter(fw);
bw.write(값); // 값을 스트림에 쓰기
bw.flush(); // 스트림의 내용을 목적지로 분출
bw.close(); // 연결 끊기

 

- 예제

 

 

1
2
3
4
5
6
7
public static void main(String[] args) {
     UseFileWrite ufw = new UseFileWrite();
     ufw.octalStream();
     System.out.println("------------------");
     ufw.hexStream();
}// main
 
cs


* 파일 복사

1. 대상파일연결

1
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("경로");
cs

2. 읽어들임

1
2
3
4
5
String temp = "";
while ((temp=br.readLine())!=null){
bw.write(temp);
bw.flush();
}
cs

3. 출력

1
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("경로")));
cs

예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package day0310;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
 
/**
* 파일을 읽어들여서 파일을 쓰는 (복사) 스트림의 사용
*
*/
public class FileCopy {
     public FileCopy() throws FileNotFoundException, IOException {
         
   File infile = new File("c:/dev/temp/java_read.txt"); // 1.읽어올 파일
   File outfile = new File("c:/dev/temp/java_read.backup.txt");//2.내보낼파일         
          /*
          //16bit 스트림 연결(문자열 파일 읽고 쓰기 가능, jpg 불가)
          BufferedReader br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(infile))); // 2. 읽기 스트림
          BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(outfile)));// 3. 쓰기 스트림    
          // 대상파일을 읽어들인다.         
          String temp = "";
          while ((temp = br.readLine()) != null) {
               // 한줄 읽어들인 내용을 출력 스트림에 기록
               bw.write(temp);
               bw.write("\n");
               // 스트림의 내용을 분출
               bw.flush();
          }//while    
          bw.close();
          br.close();*/
 
          //1. 8bit 스트림 연결(모든 파일을 읽고 쓸수 있다. jpg 가능)
          FileInputStream fis=new FileInputStream(infile);
          FileOutputStream fos = new FileOutputStream(outfile);
          //2. 파일의 내용 읽기
          int temp = 0;
          while((temp=fis.read())!=-1){
               //3. 읽어들인 내용 스트림에 쓰기
               fos.write(temp);
          }
          //4. 분출
               fos.flush();
          //5. 연결 끊기
               fos.close();
               fis.close();    
     }// filecopy
 
     public static void main(String[] args) {
          try {
               new FileCopy();
          } catch (FileNotFoundException e) {
               System.err.println("파일의 경로를 확인하세요");
               e.printStackTrace();
          } catch (IOException e) {
               System.err.println("입, 출력 예외");
               e.printStackTrace();
          }
     }
}
cs


* 객체 JVM 외부로 내보내고, 읽어들이기

- marshall Stream
8bitUnmashallingObjecInputStream조각난 객체를 읽어들여 조립
8bitMarshallingObjectOutputStream객체를 일정 크기로 잘라서 내보냄

- 크기가 다양한 객체는 Stream을 타고 JVM 외부로 나갈 수 없다.
 객체(instance) : class(설계도)에서 JVM 사용하기 위하여 메모리(heap)를 할당받아서 올려놓는것.

- 기본형 데이터형은 직렬화(쪼개기)가 되지만 객체는 직렬화가 안된다.(직렬화를 할수있게 만드는 interface가 존재.java.io.Serializable)
. 직렬화 방지는 transient 키워드로 수행한다.  // transient int i;    transient String s;

'컴퓨터 관련 > JAVA 강의' 카테고리의 다른 글

java #31 Thread, 채팅프로그램, static import   (0) 2016.12.18
java #30 Network, Port   (0) 2016.12.18
java #28 IO Stream -입력-   (0) 2016.12.18
java #27 Exception Handling, 예외처리   (0) 2016.12.18
java #26 Map   (0) 2016.12.18