키보드 입력 ➡ 프로그램(byte[]) 저장 ➡ 모니터 출력 을 반복적으로 실행
close();를 스트림별 별도로 작성InputStream in = System.in;
OutputStream out = System.out;
byte[] buf = new byte[1024];
int len = -1;
try {
while( (len = in.read(buf)) != -1 ) { //EOF까지 반복적으로 입력을 받음
out.write(buf, 0, len);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//입력 스트림 닫기
try {
if(in != null) in.close();
} catch (IOException e) {
e.printStackTrace();
}
//출력 스트림 닫기
try {
if(out != null) out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try-catch + Autoclosable interface
close()() 괄호를 적용 👉🏻 괄호에는 입출력 객체를 선언byte[] buf = new byte[1024];
int len = -1;
try( InputStream in = System.in;
OutputStream out = System.out ) {
while( (len = in.read(buf)) != -1 ) {
out.write(buf, 0, len);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
파일의 정보를 관리하는 클래스 👉🏻 파일의 내용물은 관리할 수 없음
프로그램이 시작된 위치를 기준으로 . 으로 표현하며 시작클래스 패스, class pathFile file = new File("파일 경로", "파일 이름");
file.length(); / 파일의 크기
file.exists(); / 파일 존재여부 확인
file.isFile(); / 파일인지?
file.isDiretory(); / 폴더인지?
System.out.println( file );
➡ 파일의 주소 출력(파일경로/파일이름)
File file = new File("./src/java13_io/fileStream/", "input");
//파일 존재여부 확인
if( !file.exist() ) {
System.out.println("[SYSTEM] 파일이 존재하지 않습니다.");
return; //👉🏻 파일이 존재하지 않으면 main() 중단
}
//퍄일 저장 및 읽기
byte[] buf = new byte[1024];
int len = -1;
StringBuilder sb = new StringBuilder();
try( FileInputStream fis = new FileInputStream(file) ) {
for((len = fis.read(buf)) != -1) {
sb.append(new String(buf, 0, len)); //입력받은 데이터를 StringBuilder에 추가
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(sb);
//➡ 입력된 데이터 출력
File file = new File("./src/java13_io/fileStream/", "input");
try( FileoutputStream fos = new FileOutputStream(file, true) ) {
String massage = "Study hard";
fos.write(massage.<getbytes(), 0, massaga.length());
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}