본문 바로가기
Code/Console

[Java Code] 입출력 스트림 - 예제 모음

by 스응 2023. 3. 3.
728x90
728x90

엔터 키를 누를 때까지 반복해서 값을 입력받기

// 엔터 키를 누를 때까지 반복해서 값을 입력받기 (엔터 키 = '\n')

int i;
while ( (i = System.in.read()) != '\n' ) {
    System.out.print((char) i);
}

 

특정 파일의 모든 글자 읽어오기

// 특정 txt 파일의 모든 글자 읽기 (엔터 키, 공백도 포함)

FileInputStream fis변수명 = null;

try {
    // 여기 입력하는 파일은 이미 존재하는 파일
    fis변수명 = new FileInputStream("경로/파일명.txt");
    // 한글이 포함되었을 경우, 문자 스트림 FileReader 활용
    
    int i; // i는 데이터를 1byte씩 가져올 임의의 변수명
    
    while ( (i = fis변수명.read()) != -1 ) {
        System.out.print((char) i);
    }
    
} catch (Exception e) {
    ...
} finally {
    try {
        // 스트림 메모리 해제
        fis변수명.close();
    } catch (IOException e){
        ...
    }
}

 

특정 파일에서 배열 크기만큼의 글자 읽어오기

// 특정 파일에서 배열의 크기만큼의 글자 읽기

FileInputStream fis변수명 = null;

try {
    // 여기 입력하는 파일은 이미 존재하는 파일
    fis변수명 = new FileInputStream("경로/파일명.txt");
    
    byte[] 배열명 = new byte[길이];
    
    fis변수명.read(배열명);
    
    for (byte 요소변수 : 배열명) {
        System.out.println((char) 요소변수);
    }
    
} catch (Exception e) {
    ...
} finally {
    try {
        // 스트림 메모리 해제
        fis변수명.close();
    } catch (IOException e){
        ...
    }
}

 

배열 크기만큼의 글자들을 파일에 출력하기

// 배열 크기만큼의 글자들을 파일에 출력하기

FileOutputStream fos변수명 = null;

try {
    fos변수명 = new FileOutputStream("경로/파일명.txt");
    // 한글이 포함되었을 경우, 문자 스트림 FileWriter 활용
    
    byte[] 배열명 = new byte[길이];
    
    for (int i = 0; i < 배열명.length; i++) {
        // 엔터 키, 스페이스 키도 글자 개수에 포함됨
        배열명[i] = (byte) System.in.read();
    }
    
    fos변수명.write(배열명);
    
} catch (Exception e) {
    ...
} finally {
    try {
        // 스트림 메모리 해제
        fos변수명.close();
    } catch (IOException e){
        ...
    }
}


파일 복사 및 작업 시간 계산 (보조 스트림 활용)

public static void main(String[] args) {

    long millisecond = 0;

    FileInputStream fis = null;
    FileOutputStream fos = null;

    try {
        fis = new FileInputStream("bubble.zip");
        fos = new FileOutputStream("bubblecopy.zip");
        int i;

        // 보조 스트림의 생성자 매개변수에 기반 스트림을 받음
        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        // 작업 전 현재 시간
        millisecond = System.currentTimeMillis();

        while ((i = bis.read()) != -1) {
            // i라는 공간 안에 zip 파일을 byte 단위로 읽는 중
            bos.write(i);
        }

        // 로직의 작업 시간 계산 = 작업 후 현재 시간 - 작업 전 시간
        millisecond = System.currentTimeMillis() - millisecond;

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fis.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    System.out.println("파일 복사 시 소요 시간 : " + millisecond);

} // end of main

 

320x100
반응형

댓글