(Java programming) File I/O

soosoorim·2024년 2월 20일
0

File I/O
File Input/Output 으로 파일을 읽고 쓰는 방법

File Input: 파일 읽기
File System에서 Java로 Input

File Output: 파일 쓰기
Java에서 File System으로 Output

Java 1.8 이전까지는 I/O가 매우 어렵고 복잡했으나
Java 1.8 부터 비교적 간편해졌으며, 코드를 분석하기도 쉬워졌다.

파일의 기본적인 정보 얻어오기

Java의 File 객체를 통해 파일의 기본적인 정보를 얻어올 수 있다.
파일의 절대 경로, 파일의 크기 등등

File file = new File("C:\\Java Exam", "Java Exam.txt"); // (\\는 경로의 구분)
System.out.println(file.exists()); // 파일이 존재하는지 여부 확인
System.out.println(file.isFile()); // 파일 객체인지 확인
System.out.println(file.isDirectory()); // 폴더 객체인지 확인
System.out.println(file.getAbsolutePath()); // 파일의 절대경로 확인
System.out.println(file.getName()); // 파일의 이름 확인
System.out.println(file.length()); // 파일의 크기(byte) 확인 // long타입으로 반환
System.out.println(file.lastModified()); // 파일이 마지막으로 수정된 시간
Date date = new Date(file.lastModified());
System.out.println(date);
System.out.println(file.getParent()); // 파일이 존재하는 경로
// 객체가 폴더일 경우, 폴더내에 존재하는 모든 항목의 목록
System.out.println(file.listFiles());

UTF-8 -> 다국어를 표현할 때, 대부분 3byte
UTF-16 -> 다국어 + 중국 모든 한자까지 표현 가능

read 파일을 읽어 내용을 출력하는 코드 (Java 1.8 미만)

  • 기본형
public static void main(String[] args) {
    File file = new File("C:\\Java Exam", "Java Exam.txt");
    if ( file.exists() && file.isFile() ) {
        // C:\Java Exam\Java Exam.txt이 존재하며
        // C:\Java Exam\Java Exam.txt가 파일이라면
        FileReader reader = null;
        BufferedReader bufferedReader = null;
        try {
            // 파일을 바이트 단위로 읽어오는 FileReader를 선언
            reader = new FileReader(file, Charset.forName("UTF-8"));
            // 파일을 라인 단위로 읽어오는 BufferedReader를 선언
            bufferedReader = new BufferedReader(reader);
            // 파일을 라인단위로 읽어와 할당하기 위한 String 변수 선언
            String line = null;
            // 파일이 끝날 때 까지(EOF) 반복하며 line 변수에 한 줄 씩 읽어오기
            while ( (line = bufferedReader.readLine()) != null ) {
                // 읽어온 라인을 출력
                System.out.println(line);
            }
        } catch(IOException ioe) {
            // 파일을 읽다가 예외 발생하면 예외 메시지만 출력
            System.out.println(ioe.getMessage());
        }
        finally {
			// 파일을 끝까지 읽었거나 예외가 발생했을 경우
            // BufferedReader를 닫아준다. (// 연 순서로 닫아준다. 나중에 연걸 먼저닫기)
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                }
                catch(IOException ioe) {}
			}
            // 파일을 끝까지 읽었거나 예외가 발생했을 경우
            // FileReader를 닫아준다.
            if (reader != null) {
                try {
                    reader.close();  // close안해주면 메모리 누수가 발생
                }
                catch(IOException ioe) {}
            }
        }
    }
}    

write 파일을 써서 생성하는 코드 (Java 1.8 미만)

  • 기본형
public static void main(String[] args) {
    File file = new File("C:\\java\\outputs", "java_output.txt");
    if ( ! file.getParentFile().exists() ) {
        file.getParentFile().mkdirs();
    }
    int index = 2;
    while ( file.exists() ) {
        file = new File("C:\\java\\outputs", 
                        "java_output (" + (index++) + ").txt");
    }
    FileWriter fw = null;
    BufferedWriter bw = null;
    
    try {
        fw = new FileWriter(file, Charset.forName("UTF-8"));
        bw = new BufferedWriter(fw);
        bw.write("파일을 씁니다1.\n");
        bw.write("파일을 씁니다2.\n");
        bw.write("파일을 씁니다3.\n");
        bw.flush();
    }
    catch(IOException ioe) {
        System.out.println(ioe.getMessage());
    }
    
    finally {
        if (bw != null) {
            try {
                bw.close();
            }
            catch(IOException ioe) {}
        }
		if (fw != null) {
            try {
                fw.close();
            }
            catch(IOException ioe) {}
        }
            }
    System.out.println(file.getAbsolutePath());
}   

간편해진 파일 읽어오는 방법 (Java 1.8 이상)

package file_io.readfile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * Java 1.8 버전 이상에서 사용할 수 있는 파일 읽기 예제
 * new io 사용
 */
public class NewIOReadAndPrintExam {
	
	
	public static void main(String[] args) {
		
		File file = new File("C:\\Java Exam", "Java Exam.txt");
		if (file.exists() && file.isFile()) {
			List<String> fileLine = new ArrayList<>();
			
			try { // 파일을 처음부터 끝까지 모두 읽어와 List에 할당
//				Path filePath = Paths.get("C:\\Java Exam", "Java Exam.txt");
//				Charset utf8 = Charset.forName("UTF-8");
//				fileLine.addAll(Files.readAllLines(filePath, utf8));
				// Pipe가 자동으로 Close 된다
				// 위 3줄 코드를 이 한줄로 줄읠 수 있다
				fileLine.addAll(Files.readAllLines(file.toPath(), Charset.forName("UTF-8")));
			}// 파일을 읽다가 예외가 발생했을 때, 예외 내용만 출력
			catch (IOException ioe) {
				System.out.println(ioe.getMessage());
			} // 읽어온 파일을 모두 출력
			for (String line : fileLine) {
				System.out.println(line);
			}
		}
			
	}

}

메소드 재귀 호출

파일 쓰는 방법 (Java 1.8 이상)

파일 지우는 방법

0개의 댓글

관련 채용 정보