Study/Java

자바 입출력

토기발 2022. 4. 8. 16:46

오늘은 자바 입출력에 대해 정리하겠습니다.

 

*입력/출력은 cpu기준입니다.*

  입력: cpu에 입력(콘솔창에 입력) 

  출력: cpu에서 외부에 출력(ex: txt파일)

 

 

 

import java.io.*;
//텍스트 출력
public class Test01 {
	public static void main(String[] args) throws IOException{
		File dir = new File("C:\\**\\***");
		File file = new File(dir,"aaa.txt");

 

File dir = new File("경로")

경로 설정

File file = new File(dir,"aaa.txt");

경로에 있는 텍스트 파일을 찾는데, 만약 파일이 없다면 FileNotFoundException 에러가 발생합니다.

 


1. FileWriter

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
import java.io.*;
//텍스트 출력
public class Test01 {
    public static void main(String[] args) throws IOException{
        File dir = new File("C:\\**\\***");
        File file = new File(dir,"aaa.txt");
        
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter pw = new PrintWriter(bw);
        //텍스트 형태로 들어감(String)
        int a = 10;
        pw.print("안녕하세요!");
        pw.println("자바공부 합시다.");
        pw.println("자바자바."+a);
        
        pw.close();
    }
}
 
cs

텍스트 형태(문자 단위, String)로 파일에 출력됩니다.

파일이 없는 경우 새로 생성하여 문구를 출력합니다.

 

2. FileReader

 

1
2
3
4
5
6
7
8
9
10
FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        
        while(true) {
            String str = br.readLine();
            if(str == null)break//text입력에서의 끝은 null이다.
            System.out.println(str);
        }
        
    }
cs

파일로부터 문자 단위로 읽어들이는 클래스입니다.

int를 입력해도 String으로 출력되기 때문에 int로 입력받고자 할 때는 형변환이 필요합니다.  

더불어 readLine(); 을 사용할 때는 예외처리가 꼭 필요합니다. 

throws IOException 이나 try{}catch를 사용하여 예외처리를 합니다.

 

 

3. FileOutputStream / ObjectOutputStream

 

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
import java.io.*;
 
 
class A03 implements Serializable{
    private int a;
    private int b;
    private transient int c;
    //I/O나 네트워크에서 객체를 전송할 때 멤버필드 중 전송하지 않겠다는 표시 
    public A03() {
        a = 10;
        b = 20;
        c = 30;
    }
    
    public void disp() {
        System.out.println("a = " +a);
        System.out.println("b = " +b);
        System.out.println("c = " +c);
    }
}
 
public class Test03 {
    public static void main(String[] args) throws IOException{
        File dir = new File("C:\\**\\***");
        File file = new File(dir,"bbb.txt");
        
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        
        A03 ap = new A03();
        
        oos.writeObject(ap);
        oos.close();
        
    }
    
}
 
cs

FileOutputStream 은 파일을 바이트단위로 출력합니다.

바이트단위로 출력하기 때문에 텍스트 파일을 열어보면 정상적이지 않은 문자가 확인됩니다.

따라서 해당 데이터를 입력받을 때는 FileInputStream 클래스를 사용해야 합니다.

 

ObjectOutputStream 는 객체를 파일에 쓰는 클래스입니다.

반대로 객체를 읽을 때는 ObjectInputStream 를 사용합니다.

ObjectOutputStream를 사용할 때는 Serializable 인터페이스를 사용해서 객체를 스트림으로 바꿔주어야 합니다.

또, ObjectOutputStream 만으로는 파일에 접근하지 못해 FileOutputStream 을 먼저 사용해야 합니다.

 

 

4. FileInputStream / ObjectInputStream 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.*;
 
 
public class Test04 {
    public static void main(String[] args) throws IOException, ClassNotFoundException{
        File dir = new File("C:\\**\\***");
        File file = new File(dir,"bbb.txt");
        
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new     BufferedInputStream (fis);
        ObjectInputStream ois =    new ObjectInputStream(bis);
        
        Object obj = ois.readObject();
        A03 ap = (A03)obj;
        ap.disp();
    }
}
 
 
cs

FileInputStream은 바이트단위로 출력한 텍스트를 입력받습니다. 

위에 설명한 ObjectOutputStream과 마찬가지로 ObjectInputStream도 스스로 파일에 접근하지 못해

FileInputStream 을 먼저 사용해야 합니다.

 

 

*문자단위/ Byte단위 구분

 

Byte 단위

InputStream / FileInputStream

OutputStream / FileOutputStream 

 

문자 단위

Reader / FileReader

Writer / FileWriter

 

 

 

참고 출처 : https://blog.naver.com/highkrs/220476927234