● 프로그램의 상당 부분은 다음 대상의 입출력과 관련이 있다. 그리고 이들에 대한 자바의 입출력 방식을 가리켜 I/O 모델이라고 한다. 1바이트씩 쓰는게 일반적이다.
● 입출력 스트림
package org.example;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public Main() {
fileWrite();
fileRead();
}
private void fileWrite() {
// close 를 무조건 해줘야 한다.
try {
FileOutputStream fos = new FileOutputStream("date.dat");
try {
fos.write(7);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void fileRead() {
FileInputStream fis = null;
try {
fis = new FileInputStream("date.dat");
int dat = fis.read();
System.out.println(dat);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Main();
}
}
close 를 해줘야 한다.
finally 를 쓰게 되면 try 문에 fis 매서드가 있기때문에 밖에다가 null값을 지정해 줘야 한다.
close 를 쓰지 않을려면 try문에다가 객체 생성을 해주면 된다.
기본적으로 1바이트씩 읽는다.
● 바이트 단위의 입출력 스트림
package org.example;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Main2 {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("aa.pptx");
FileOutputStream fos = new FileOutputStream("bb.pptx");
) {
byte buf[] = new byte[1024];
int len;
while (true) {
len = fis.read();
if (len == -1) {
break;
}
fos.write(buf,0,len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
1024 바이트로 읽게 되면 속도가 훨씬 빨라진다.