Java
FileInputStream 이용하여 File 객체 읽기
kwanghyup
2020. 6. 15. 02:30
import java.io.*;
// FileInputStream을 사용하여 File객체 읽기
public class FileInputStreamExam01 {
String path; // 읽을 파일의 경로
File file; // 읽을 파일 객체
FileInputStream is; // 파일 객체를 읽을 FileInputStream
public FileInputStreamExam01() throws FileNotFoundException {
path = FileInputStreamExam01.class.getResource("FileInputStreamExam.class").getPath();
file = new File(path); // 파일 객체에 경로 할당
is = new FileInputStream(file); // 파일 객체를 FileInputStream에 전달
} // constructor end
public static void main(String[] args) throws IOException {
FileInputStreamExam01 fis = new FileInputStreamExam01();
File file = fis.file; // 파일 객체
InputStream is = fis.is; // 파일 객체를 담은 FileInputStream
fis.fileInfo(file);
fis.readFileByInputStream(is);
} //main -end
public void fileInfo(File file){ // file 객체의 여러가지 메서드
System.out.println("파일 경로: " + file.getPath());
System.out.println("부모 디렉토리 : "+file.getParent());
System.out.println("실행가능 여부 : "+file.canExecute());
System.out.println("읽기가능 여부 : "+file.canRead());
System.out.println("쓰기,수정 가능 여부 :" + file.canWrite());
System.out.println("파일 이름: " + file.getName());
System.out.println("숨김 파일인지 여부 :" +file.isHidden());
System.out.println("URI 표현 : " + file.toURI());
System.out.println("파일의 크기 : " + file.length() +" byte");
} // fileInfo - end
// FileInputStream을 사용하여 File 객체 읽기
public void readFileByInputStream(InputStream is) throws IOException {
byte[] bytes = new byte[400]; // 바이트 배열
int loop = 0; // 반복수
while ((is.read(bytes))!=-1) {
System.out.write(bytes); // 읽은 데이터 콘솔에 출력
loop++;
} //while end
System.out.println("반복수 : " + loop);
} // fileInputStream - end
}