[JAVA] - File I/O

Shim31·2023년 6월 6일

Java

목록 보기
4/5

Stream : flow of input/output data

input stream : 프로그램으로 데이터를 읽어옴

ex) 파일에서 데이터를 읽거나 네트워크 연결을 통해 데이터를 수신

output stream : 프로그램에서 데이터를 씀

ex) 파일에 데이터를 쓰거나 네트워크를 통해 데이터를 전송



File I/O의 adventage

  • 파일은 영구적 데이터, 메모리는 끄면 사라짐
  • 한 프로그램에서 다른 프로그램으로 데이터 전달 할 때 파일로 전달 가능
  • 모든 입력 데이터를 파일에 저장하여 프로그램이 자동으로 파일을 읽게 할 수 있음
    • 하나 하나 입력해서 작성 하지 않아도 됨

파일의 종류

종류나타나는 예시(127)예시
Text files‘1’, ‘2’, ‘7’로 저장java 소스 코드, txt 파일
Binary files7F(16진수) (127로 저장)jpg, img, mp3, avi

*PrintWriter를 사용한 text file write*


PrintWriter

메모리 버퍼에 먼저 저장하고 버퍼가 가득차거나, close를 했을 때 파일에 저장 됨

Method

  • .write → 문자열을 파일에 바이트 단위로 작성
    • (줄바꿈 문자('\r\n' 등)를 직접 포함)
    • IOException을 처리해야 됨
  • .println → 문자열을 파일에 출력
    • 줄바꿈 기호('\n')를 자동으로 추가
    • IOException을 처리햐야 됨
import java.io.IOException;
import java.io.PrintWriter;

public class Sample {
    public static void main(String[] args) throws IOException {
				try{
				 PrintWriter pw = new PrintWriter("c:/out.txt");
	       for(int i=1; i<11; i++) {
            String data = i+" 번째 줄입니다.";
            pw.println(data);}
       //println이라는 메써드를 사용함
       //줄바꿈 기호 필요 없음
				}catch(IOException e){
						System.out.println(e.getMesssge());
				}finaly{
	        pw.close(); //닫아줌
					//안닫으면 데이터 저장 안됨
				}        
    }
}

**PrintWriter pw = new PrintWriter("c:/out.txt");**

→ 새로운 파일을 만듬

원래 존재하던 파일이라면 데이터 삭제됨

PrintWriter로 파일에 내용 추가하기

True 모드로 열기!

import java.io.FileWriter;
import java.io.IOException;

public class Sample {
    public static void main(String[] args) throws IOException {

			try{
				 //추가모드로 열꺼임
        FileWriter fw2 = new FileWriter("c:/out.txt", true);  // 파일을 추가 모드로 연다.
        for(int i=1; i<21; i++) {
						//이 두줄 대신 fw2.println(""); 해도됨
            String data = "i+ 번째 줄입니다.\r\n";
            fw2.write(data);
        }
				}catch(IOException e){ //예외처리 해줘야함
						System.out.println(e.getMesssge());
				}finaly{
	        fw2.close(); //닫아줌
					//안닫으면 데이터 저장 안됨
				}     
        
    }
}



Scanner를 사용한 text file read


Scanner

Scanner 객체 생성자에 File 객체를 넣어줘야함

  1. File 객체 생성
    1. 읽을 파일을 가리키는 File 객체를 생성
    2. 파일의 경로나 파일 객체를 통해 파일을 지정
  2. Scanner 객체 생성
    1. Scanner 클래스의 생성자를 사용하여 파일을 읽을 준비
    2. Scanner 생성자에 File 객체를 전달
  3. 파일 읽기
    1. .nextInt(), .nextLine() 등의 메서드 사용 해서 데이터 읽기
    2. .hasNext(), .hasNextInt(), hasNextLine(), .hasNextDouble를 사용해 다음 요소가 존재하는지 확인 가능
  4. close

//파일 읽기
		Scanner inputStream=null;
		try {
			File file = new File(fileNm); 
			inputStream=new Scanner(file); //Scanner 생성자에 File 객체 전달
			
			
		}catch(FileNotFoundException e) {
			System.out.println("Error open file "+e.getMessage());
			System.exit(0);
		}
		//다음 줄이 없으면 파일 읽기 멈춰!
		while(inputStream.hasNextLine()) {
			System.out.println(inputStream.nextLine());
		}
		
		inputStream.close();


Scanner는 모든 종류 데이터에 대해 읽을 데이터가 남아있는지 체크하는 메소드가 있음 (boolean type으로 리턴)

.hasNext() → .next()로 읽을 수 있는 데이터가 있는지

.hasNextDouble() → .nextDouble()로 읽을 수 있는 데이터가 있는지

.hasNextInt() → .nextInt()로 읽을 수 있는 데이터가 있는지

.hasNextLine() → .nextLine()로 읽을 수 있는 데이터가 있는지

File class

.canRead() → 읽을 수 있는지 (boolean type)

.canWrite() → 수정 가능 한지 (boolean type)

.delete() → 파일 지우기

.getName() → 파일 이름 반환

.getPath() → 파일 위치 반환

.length() → 파일의 바이트 단위 반환(Long)

File file = new File("text.txt");
File file2 = new File("C:\\homework\\texts.txt");
// 역슬래쉬로 표현 (/ 대신 \\로 씀)




+ splite 사용

splite 사용하여 파일의 자료를 읽고 편하게 분리할 수 있음

String arr= "1020,23,324325,33"
String [] save=arr.split(",");
System.out.println(save[0]); //1020
System.out.println(save[1]); //23
System.out.println(save[2]); //324325
System.out.println(save[3]); //33



ObjectOutPutStream*를 사용한 binary file write*


FileOutPutStream 사용해도 됨

ObjectOutPutStream

→ 생성자로 FileOutPutStream 객체를 받음

Method

.writeInt()

.writeLong()

.writeDouble()

.writeFloat()

.writeObject()

.writeUTF()

try{	
			//바이너리 파일 쓰기
			ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileNm));
			for(int i=0;i<10;i++) {
				//이건 print가 아니라 write뭐시기
				if(i==0)
					outputStream.writeInt(saveVal[i]);
				else
					outputStream.writeInt(saveVal[i]-saveVal[i-1]);
			}
			

}catch(FileNotFoundException e) {
			System.out.println("Error open file "+e.getMessage());
			System.exit(0);
}catch(IOException e3) {
			System.out.println("Error IO"+e3.getMessage());
			System.exit(0);
}finaly{
			outputStream.close();
}



ObjectInPutStream*를 사용한 binary file read*


FileInPutStream 사용해도 됨

ObjectInPutStream

→ 생성자로 FileInPutStream 객체를 받음

Method

.readInt()

.readLong()

.readDouble()

.readFloat()

.readObject()

.readUTF()

try{	
			//바이너리 파일 읽기
			ObjectInputStream inputStream2 = new ObjectInputStream(new FileInputStream(fileNm));
			
			//파일 읽기
			//10개 정수 읽음
			int result=0;
			int i=1;
			while(i<=10){
				result=inputStream2.readInt();
				System.out.println(i+"번 "+ result);
				i++;
			}

}catch(FileNotFoundException e) {
			System.out.println("Error open file "+e.getMessage());
			System.exit(0);
}catch (EOFException e2) { //IOException 위에 싸야함,  IO에 파일 끝 도달 예외도 포함됨
	     System.out.println("Error EOF " + e2.getMessage());
	     System.exit(0);
}catch(IOException e3) {
			System.out.println("Error IO"+e3.getMessage());
			System.exit(0);
}finaly{
			inputStream2.close();
}

EOFException → 파일 끝에 도달해 읽을 것이 없다.





Serialization( 직렬화 )

객체를 직렬화하여 바이너리 파일에 쓰기, 읽기 할 수 있음

class는 **Serializable interface****implements** 해야함

ObjectInPutStream, ObjectOutPutStream을 사용해 읽고 씀

**readObject()**, **writeObject()** 사용

import java.io.*;

class Person implements Serializable {
//Serializable interface를 implements

    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class SerializationExample {
    public static void main(String[] args) {
        // 객체 생성
        Person person = new Person("John Doe", 30);

        // 객체를 파일에 직렬화
        try {
            FileOutputStream fileOut = new FileOutputStream("person.ser");
            ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
            objectOut.writeObject(person); //객체를 파일에 작성
            objectOut.close();
            fileOut.close();
            System.out.println("객체를 파일에 직렬화하였습니다.");

        } catch (IOException e) {
            e.printStackTrace();
        }

        // 파일로부터 객체 역직렬화
        try {
            FileInputStream fileIn = new FileInputStream("person.ser");
            ObjectInputStream objectIn = new ObjectInputStream(fileIn);
            Person deserializedPerson = (Person) objectIn.readObject();
																			//(Person)으로 타입 맞춰줌
            objectIn.close();
            fileIn.close();

            System.out.println("파일로부터 객체를 역직렬화하였습니다.");
            System.out.println("이름: " + deserializedPerson.getName());
            System.out.println("나이: " + deserializedPerson.getAge());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

0개의 댓글