본문 바로가기

Java

자바 메모장 파일 읽어오기 (FileInputStream)

이번 글에서 알아볼 것은 FileInputStream입니다.


FileInputStream으로 파일 읽어오기

먼저  FileInputStream  은 파일을 읽어올 때 사용한다.

 read() 파일의 시작부터 차례대로 바이트 단위로 읽는 용도이다.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamEx {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
		FileInputStream fis = new FileInputStream(new File("./src/files/FileInputStreamTest파일.txt"));
		//FileInputStreamTest파일.txt를 읽어온다.
		
		int read = 0; //한글자씩 읽어 온다.
		while ((read = fis.read()) != -1) { //읽어올 값이 없으면 -1을 반환하여, while문을 나간다.
			System.out.print((char)read); //숫자를 문자로 변환해서 출력한다.
		}
		
		fis.close(); //FileInputStream을 닫아준다. (중요!)
	}

}

 

여기서 중요한 부분은  FileInputStream  를 사용했으면  close()  메소드를 통해 닫아주는 게 중요하다.

실행을 하면

 

'FileInputStreamTest파일.txt'을 출력한 내용

위 콘솔창에 메모장 내용이 출력되었다.


FileInputStream으로 한글까지 출력하기

위 내용에서 코드를 실행해보면 한글이 깨져서 출력이 된다.

 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamEx2 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		FileInputStream fis = new FileInputStream(new File("./src/files/FileInputStreamTest파일.txt"));
		
		int bufSize = fis.available(); //읽어올 수 있는 byte의 수를 반환한다.
		byte[] buf = new byte[bufSize]; //bufSize 만큼의 byte 배열을 선언한다.
		
		fis.read(buf);
		System.out.println(new String(buf)); //바이트 배열을 문자열로 변환한 값을 출력한다.
		fis.close();
		
	}

}

 

위 코드로 작성하여 실행을 했을 경우 한글이 깨지는 현상을 막으면서 출력할 수 있다.

 

한글이 정상적으로 출력됬다.

 

이 외에 다른  FileReader , BufferReader 를 통해서도 파일을 읽어 올 수 있다.