바이트배열(문자열) 단위로 입력하거나 출력하는 클래스
InputStream FileInputStream, ByteArrayInputStream, FilterInputStream
FileOutputStream, ByteArrayOutputStream, FilterOutputStream
package sec1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
// 키보드로 문자를 입력받아 out2.txt로 저장
// 그 내용을 불러와 콘솔창에 다시 출력
public class StreamEx2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 파일에 값을 저장
FileOutputStream fos;
try {
fos = new FileOutputStream("out2.txt");
String s = sc.nextLine(); // String 형태로 입력
byte[] b = s.getBytes(); // byte 배열로 변환
fos.write(b); // 바이트로 파일에 데이터 입력
fos.close(); // 입력 종료
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
// 파일을 불러와서 값을 가져옴
FileInputStream fis;
try {
fis = new FileInputStream("out2.txt");
// 1. 한 글자씩 불러와서 읽어 처리하는 방식
byte b;
while((b = (byte) fis.read()) != -1) {
System.out.print((char) b);
}
// 2. 한번에 모든 글자를 불러와서 처리하는 방식
// byte[] b = fis.readAllBytes();
// System.out.println(new String(b));
fis.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
얘는 쓸일이 많이 없으니 이런게 있다고만 알고있자
package sec2;
import java.io.*;
/*
한글과 같은 캐릭터 셋을 지정하여 출력할 수 있음
기본 셋 UTF8
처음에 NULDLE 가 생기는데 이것은 데이터의 시작을 의미한다. | 지우면 안 됨
지정 순서
File -> FileOutputStream -> BufferedOutputStream -> DataOutputStream
* */
public class DataOutputStreamEx1 {
public static void main(String[] args) {
File file = new File("out7.txt");
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
FileOutputStream fos = null;
BufferedOutputStream bos = null;
DataOutputStream dos = null;
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
dos = new DataOutputStream(bos); // buffer를 이용해 접근해야 한다.
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
try {
dos.writeUTF("헬로우 브로"); // UTF8
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
dos.close();
bos.close();
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
// dis.readUTF();
}
}