구분 | Byte 기반 | Character 기반 | ||
---|---|---|---|---|
Input | Output | Input | Output | |
Basic | InputStream | OutputStream | Reader InputStreamReader | Writer |
OutputStreamReader | ||||
Arrays | ByteArrayInputStream | ByteArrayOutputStream | CharArrayReader | CharArrayWriter |
Files | FileInputStream RandomAccessFile | FileOutputStream RandomAccessFile | FileReader | FileWriter |
Pipes | PipedInputStream | PipedOutputStream | PipedReader | PipiedWriter |
Buffering | BufferedInputStream | BufferedOutputStream | BufferedReader | BufferedWriter |
Filtering | FilterInputStream | FilterOutputStream | FilterReader | FilterWriter |
Parsing | PushbackInputStream | |||
StreamTokenizer | PushbackReader | |||
LineNumberReader | ||||
Strings | StringReader | StringWriter | ||
Data | DataInputStream | DataOutputStream | ||
Data-Formatted | PrintStream | PrintWriter | ||
Objects | ObjectInputStream | ObjectOutputStream | ||
Utilities | SequenceInputStream |
Stream | Byte Stream | Character Stream |
---|---|---|
Source streams (입력 데이터의 시작) | InputStream | Reader |
Sink streams (데이터가 처리되어 출력되는 끝) | OutputStream | Writer |
입력스트림 | 출력스트림 | 대상 |
---|---|---|
FileInputStream | FileOutputStream | 파일 |
ByteArrayInputStream | ByteArrayOutputStream | 메모리 |
PipedInputStream | PipedOutputStream | 프로세스 |
AudioInputStream | AudioOutputStream | 오디오장치 |
InputStream | OutputStream |
---|---|
abstract int read() | abstract void write(int b) |
int read(byte[] b) | void write(byte[] b) |
int read(byte[] b, int off, int len) | void write(byte[] b, int off, int len) |
InputStream | 설명 |
---|---|
int read() | 입력 스트림에서 데이터의 다음 바이트를 read한다. 파일 끝일 경우 -1을 반환한다. |
int read(byte[] b) | byte[] b만큼의 데이터를 읽어서 b에 저장하고 읽은 바이트 수를 반환한다. |
int available() | 현재 입력스트림에서 읽을 수 있는 바이트 수의 추정치를 반환한다. |
mark() | 데이터가 읽혀진 InputStream의 위치를 표시한다. |
void close() | 현재 입력 스트림을 close 하는데 사용된다. |
OutputStream | 설명 |
---|---|
void write(int b) | 현재 출력 스트림에 바이트를 write하는데 사용된다. |
void write(byte[] b) | 현재 출력 스트림에 바이트 배열을 write하는데 사용된다. |
void flush() | 현재 출력 스트림을 flush한다. |
void close() | 현재 출력 스트림을 닫는데 사용된다. |
public class FileCopyByteEx1 {
public static void main(String[] args) throws IOException {
FileInputStream in = null; FileOutputStream out = null;
try {
in = new FileInputStream( "/Users/jongkwonkim/Documents/streamtest/testme.txt");
out = new FileOutputStream( "/Users/jongkwonkim/Documents/streamtest/copy_testme.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
바이트기반 스트림 | 문자기반 스트림 | 대상 |
---|---|---|
FileInputStream FileOutputStream | FileReader FileWriter | 파일 |
ByteArrayInputStream ByteArrayOutputStream | CharArrayReader CharArrayWriter | 메모리 |
PipedInputStream PipedOutputStream | PipedReader PipedWriter | 프로세스 |
StringBufferedInputStream StringBufferedOutputStream | StringReader StringWriter | 메모리 |
InputStream | Reader |
---|---|
abstract int read() int read(byte[] b) int read(byte[] b, int off, int len) | int read() int read(char[] char) abstract int read(char[] cbuf, int off, int len) |
OutputStream | Writer |
---|---|
abstract void write(int b) void write(byte[] b) void write(byte[] b, int off, int len) | void write(int c) void write(char[] cbuf) abstract void write(char[] cbuf, int off, int len) void write(String str) void write(String str, int off, int len) |
예제
//기반 스트림을 생성
FileInputStream fin = new FileInputStream("test.txt");
//기반 스트림을 이용한 보조 스트림 생성
BufferedInputStream bin = new BufferedInputStream(fin);
...
//보조 스트림인 BufferedInputStream으로 데이터를 읽는다
bin.read();
입력 | 출력 | 설명 |
---|---|---|
FileInputStream | FileOutputStream | 필터를 이용한 입출력 처리 |
BufferedInputStream | BufferedOutputStream | 버퍼를 이용한 입출력 성능향상 |
DataInputStream | DataOutputStream | int, float과 같은 기본형 단위(primitive type)로 데이터를 처리하는 기능 |
SequenceInputStream | SequenceOutputStream | 두 개의 스트림을 하나로 연결 |
ObjectInputStream | ObjectOutputStream | 데이터를 객체단위로 read/write하는데 사용한다. |
메서드명 | 설명 |
---|---|
int available() | 스트림으로부터 read 할 수 있는 데이터의 크기를 반환 |
void close() | 스트림을 close로써 사용하고 있던 자원 반환 |
void mark(int readlimit) | 현재위치를 표시한다. 필요시에 reset()에 의해서 표시해놓은 위치로 되돌아갈 수 있다. readlimit은 되돌아갈 수 있는 byte의 수이다. |
boolean markSupported() | mark()와 reset()을 지원하는지를 알려준다. mark()와 reset()을 사용하기 전에 markSupported()를 호출해서 지원여부를 확인해야 한다. |
abstract int read() | 1byte를 read한다(0~255 사이 값). read할 데이터가 없으면 -1을 반환한다. abstract 메서드로 InputStream을 상속하는 클래스들의 특성에 맞게 구현한다. |
int read(byte[] b) | byte 배열 b의 사이즈만큼 read한 후 데이터의 수를 반환하며 반환 값은 배열의 크기보다 작거나 같다. |
int read(byte[] b, int off, int len) | 최대 len개의 byte를 read해서, 배열 b의 off부터 저장하며, read할 수 있는 데이터가 len보다 적을 수 있다. |
void reset() | 스트림에서 위치를 마지막으로 mark() 메서드가 호출된 위치로 되돌아간다. |
long skip(long n) | 스트림에서 길이(n) 만큼 skip한다. |
메서드명 | 설명 |
---|---|
void close() | 사용하던 자원을 반환한다. |
void flush() | 스트림의 버퍼에 있는 모든 것을 출력소스에 write한다. |
abstract void write(int b) | int b 값을 출력소스에 write한다. |
void write(byte[] b) | byte 배열 b를 출력소스에 write한다. |
void write(byte[] b, int off, int len) | byte 배열 b에 저장된 내용 중에서 off 위치부터 len 만큼 read해서 출력소스에 write한다. |
byte[] buf = {35,36,37,38};
//새로운 바이트 배열 입력 스트림 생성
ByteArrayInputStream byt = new ByteArrayInputStream(buf);
int k = 0;
while((k = byt.read()) != -1){
//byte 값을 char 문자로 변환
char ch = (char) k;
System.out.println("문자의 ASCII 값: " + k + "; 특수문자: " + ch);
}
[결과]
문자의 ASCII 값: 35; 특수문자: #
문자의 ASCII 값: 36; 특수문자: $
문자의 ASCII 값: 37; 특수문자: %
문자의 ASCII 값: 38; 특수문자: &
FileOutputStream fout =
new FileOutputStream("/Users/jongkwonkim/Documents/streamtest/fout.txt");
ByteArrayOutputStream bout = new ByteArrayOutputStream();
bout.write(68);
bout.writeTo(fout);
bout.flush();
bout.close();
[결과]
/Users/jongkwonkim/Documents/streamtest/fout.txt 파일이 생성됨
파일을 열어보면 char타입 문자 'D'가 저장되어 있다
메서드명 | 설명 |
---|---|
FileInputStream(String name) | 지정 파일이름의 실제 파일과 연결된 FileInputStream을 생성한다. |
FileInputStream(File file) | 지정한 File 인스턴스로 FileInputStream을 생성한다. |
FileOutputStream(String name) | 지정 파일이름의 실제 파일과 연결된 FileOutputStream을 생성한다. |
FileOutputStream(String name, boolean append) | 지정 파일이름의 실제 파일과 연결된 FileOutputStream을 생성함에 있다. 두번째 인자인 append를 true로 하면 파일의 마지막 내용에 덧붙이며, false면 덮어쓰게 된다. |
FileOutputStream(File file) | 지정한 File 인스턴스로 FileOutputStream을 생성한다. |
class FileViewer{
public static void main(String[] args) throws IOException{
FileInputStream fis = new FileInputStream(args[0]);
int data = 0;
while((data=fis.read())!=-1){
//read return type이 int인 것은
//1byte씩 파일로부터 데이터를 읽어 들이지만 더 이상 값이 없음을 알리는 -1을 제외하고는
//0~255범위의 정수값 int가 가장 효율적이고 빠르다
char c = (char)data;
System.out.println(c);
}
}
}
try{
FileInputStream fin =
new FileInputStream("/testme.txt");
FileOutputStream fos =
new FileOutputStream("/copytestme.txt");
int data = 0;
while((data=fin.read())!=-1){
fos.write(data):
}
fin.close();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
메서드명/생성자 | 설명 |
---|---|
BufferedInputStream(InputStream in, int size) | InputStream 인스턴스를 입력소스로 지정된 크기(byte 단위)의 버퍼를 갖는 BufferedInputStream 인스턴스를 생성한다. |
BufferedInputStream(InputStream in) | InputStream 인스턴스를 입력소스로 버퍼의 크기를 지정해주지 않으면 Default buffer로 설정된 8,192byte 크기의 버퍼를 가지게 된다. |
BufferedOutputStream(OutputStream out, int size) | OutputStream 인스턴스를 출력소스로 지정된 크기(byte 단위)의 버퍼를 갖는 BufferedOutputStream 인스턴스를 생성한다. |
BufferedOutputStream(OutputStream out) | OutputStream 인스턴스를 출력소스로 버퍼의 크기를 지정해주지 않으면 Default buffer로 설정된 8,192byte 크기의 버퍼를 가지게 된다. |
flush() | 버퍼의 모든 내용을 출렷소스에 출력한 후 버퍼를 비운다. |
close() | flush()를 호출해서 버퍼의 모든 내용을 출력소스에 출력하고, BufferedOutputStream 인스턴스가 사용하던 모든 자원을 반환한다. |
public class BufferedInputStream extends FilterInputStream{
private static int DEFAULT_BUFFER_SIZE = 8192;
}
public class BufferedOutputStream extends FilterOutputStream{
public BufferedOutputStream(OutputStream out){
this(out, 8192);
}
}
try{
FileOutputStream fos =
new FileOutputStream("/bufFile.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
String s = "Welcome to stream!!!";
byte[] b = s.getBytes();
bos.write(b);
bos.flush();
bos.close();
fos.close();
System.out.println("Success!");
}catch(IOException e){
e.printStackTrace();
}
[결과]
Success!
메서드명/생성자 | 설명 |
---|---|
DataInputStream(read in) | 지정한 InputStream 인스턴스를 기반스크림으로 하는 DataInputStream 인스턴스를 생성한다. |
boolean readBoolean() byte readByte() char readChar() short readShort() int readInt() long readLong() float readFloat() double readDouble() | 각 자료형에 맞는 값을 read한다. 더 이상 read할 값이 없으면 EOFException을 발생시킨다. |
String readUTF() | UTF-8형식으로 write된 문자열을 read하는 데 사용된다. |
int skipBytes(int n) | 현재 read하고 있는 위치에서 지정된 n 만큼 skip한다. |
메서드명/생성자 | 설명 |
---|---|
DataOutputStream(OutputStream out) | 지정한 OutputStream 인스턴스를 기반스트림으로 하는 DataOutputStream 인스턴스를 생성한다. |
void writeBoolean(boolean b) void writeByte(int b) void writeChar(int c) void writeShort(int s) void writeInt(int i) void writeLong(long l) void writeFloat(float f) void writeDouble(double d) | 각 자료형에 맞는 값을 write한다. |
void writeUTF(String s) | UTF 형식으로 문자를 출력한다. |
void writeChars(String s) | 지정한 문자열을 write한다. writeChar(char c) 메서드를 여러번 호출한 결과와 같다. |
int size() | 지금까지 DataOutputStream에 write된 byte 수를 알려준다. |
public class DataOutputStreamEx2 {
public static void main(String[] args) throws IOException {
String filename="data.txt";
//노드 연결(노드 스트림 연결)
FileOutputStream fos = new FileOutputStream(filename);
//필터 스트림과 노드 스트림을 연결
DataOutputStream dos = new DataOutputStream(fos);
byte b=65;
byte[] buf={66,67,68};
short s=100;
char ch='가';
boolean bool=true;
double d=123.45;
String str="홍길동";
dos.write(b);
dos.write(buf,0,buf.length);
dos.writeShort(s);
dos.writeChar(ch);
dos.writeBoolean(bool);
dos.writeDouble(d);
dos.writeUTF(str);
System.out.println(dos.size()+"bytes 기록");
// 스트림에 남아있는 데이터가 있으면 flush
dos.flush();
dos.close();
}
}
👇
public class DataInputStreamEx2 {
public static void main(String[] args) throws IOException {
DataInputStream dis = new DataInputStream(
new FileInputStream("data.txt"));
System.out.println(dis.available()+"바이트 읽어들이기");
// 파일에 쓴 순서대로 읽어야 함
byte a=dis.readByte();
System.out.println(a);
byte[]ba=new byte[3];
int n=dis.read(ba);
for(byte b:ba){
System.out.println(b);
}
short s=dis.readShort();
System.out.println(s);
System.out.println(dis.readChar());
System.out.println(dis.readBoolean());
System.out.println(dis.readDouble());
System.out.println(dis.readUTF());
dis.close();
}
}
[결과]
28바이트 읽어들이기 65
66
67
68
100
가
true
123.45
홍길동
메서드명/생성자 | 설명 |
---|---|
SequenceInputStream(Enumeration e) | Enumeration에 저장된 순서대로 입력스트림을 하나의 스트림으로 연결한다. |
SequenceInputStream(InputStream s1, InputStream s2) | 두 개의 입력스트림을 하나로 연결한다. |
FileInputStream input1=
new FileInputStream("/testme.txt");
/*
* testme.txt 파일 내용
* Welcome!
* test file
* Goodbye~
*/
FileInputStream input2=
new FileInputStream("/bufFile.txt");
/*
* bufFile.txt 파일 내용
* Welcome to stream!!!
*/
SequenceInputStream inst=new SequenceInputStream(input1, input2);
int j;
while((j=inst.read())!=-1){
System.out.print((char)j);
}
inst.close();
input1.close();
input2.close();
[결과]
Welcome!
test file
Goodbye~Welcome to stream!!!
format | 설명 | 결과 |
---|---|---|
%d | 10진수 | 65 |
%o | 8진수(octal integer) | 101 |
%x | 16진수(hexadecimal integer) | 41 |
%c | 문자 | A |
%s | 문자열 | 65 |
%5d | 5자리 숫자, 빈자리는 공백으로 채운다 | 65 |
%05d | 5자리 숫자, 빈자리는 0으로 채운다 | 65 |
\t | 탭(tab) | |
\n | 줄바꿈 문자(new line) |
메서드명 | 설명 |
---|---|
abstract void close() | 입력스트림을 close하면서 사용하던 자원을 반환한다. |
void mark(int readlimit) | 현재 위치를 표시해놓는다. 나중에 reset()에 의해서 표시해 놓은 위치로 다시 되돌아갈 수 있다. |
boolean markSupported() | mark()와 reset() 지원여부를 확인해준다. |
int read() | 입력소스로부터 하나의 문자를 read한다. char의 범위인 0~65535범위의 정수를 반환하며, 입력스트림의 마지막 데이터에 도달하면 -1을 반환한다. |
int read(char[] c) | 입력소스로부터 매개변수로 주어진 배열 c의 크기만큼 읽어서 배열 c에 저장한다. read해 온 데이터의 개수 또는 -1을 반환한다. |
boolean ready() | 입력소스로부터 데이터를 읽을 준비가 되어있는지 확인한다. |
void reset() | 입력소스에서의 위치를 마지막으로 mark()가 호출되었던 위치로 되돌아간다. |
void skip(long n) | 현재 위치에서 전달된 n 만큼을 skip한다. |
메서드명 | 설명 |
---|---|
abstract void close() | 출력스트림을 close하면서 사용하던 자원을 반환한다. |
abstract void flush() | 스트림의 버퍼에 있는 모든 내용을 출력소스에 write한다. |
void write(int b) | 전달된 값을 출력소스에 write한다. |
void write(char[] c) | 전달된 배열 c에 저장된 모든 내용을 출력소스에 write한다. |
void write(String str) | 전달된 문자열 str을 출력소스에 write한다. |
void write(String str, int off, int len) | 전달된 문자열 str을 off번째 문자부터 len개 만큼의 문자열을 출력소스에 write한다. |
public class FileReaderEx01 {
public static void main(String argsp[]){} }
try {
String fileName = "/Users/jongkwonkim/Documents/streamtest/bufFile.txt";
FileReader fr = new FileReader(fileName);
int data = 0;
while((data=fr.read()) != -1){
System.out.print((char)data);
}
System.out.println();
fr.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
예제
try{
final PipedReader read = new PipedReader();
final PipedWriter write = new PipedWriter(read);
Thread readerThread = new Thread(new Runnable(){
public void run(){
try{
int data = read.read();
while(date != -1){
System.out.println((char) data);
data = read.read();
}
}catch(Exception ex){}
}
});
Thread writerThread = new Thread(new Runnable(){
public void run(){
try{
write.write("writerThread write...!\n".toCharArray());
}catch(Exception ex){}
}
});
readerThread.start();
writerThread.start();
}catch(Exception e){
e.printStackTrace();
}
[결과]
writerThread write...!
String inputData = "String message!";
StringReader input = new StringReader(inputData);
StringWriter output = new StringWriter();
int data = 0;
try{
while((data = input.read())!=-1){
output.write(data);
}
}catch(IOException e){}
System.out.println("Input Data: " + inputData);
System.out.println("Output Data: " + output.toString());
[결과]
Input Data: String message!
Output Data: String message!
public class BufferedReaderEx01 {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("/Users/jongkwonkim/Documents/streamtest/brtestfile.txt");
BufferedReader br = new BufferedReader(fr);
String line = "";
for(int i=1;(line = br.readLine())!=null;i++) {
System.out.println(i+":"+line);
}
br.close();
} catch(IOException e) {
e.printStackTrace();
}
} // main
}
[결과]
1:안녕하세요!
2:테스트 파일입니다~
메서드명/생성자 | 설명 |
---|---|
InputStreamReader(InputStream in) | OS의 기본 인코딩의 문자로 변환하는 InputStreamReader를 생성한다. |
InputStreamReader(InputStream in, String encoding) | 지정 인코딩을 사용하는 InputStreamReader를 생성한다. |
String getEncoding() | InputStreamReader의 인코딩을 알려준다. |
메서드명/생성자 | 설명 |
---|---|
OutputStreamReader(OutputStream in) | OS의 기본 인코딩의 문자로 변환하는 OutputStreamReader를 생성한다. |
OutputStreamReader(OutputStream in, String encoding) | 지정 인코딩을 사용하는 OutputStreamReader를 생성한다. |
String getEncoding() | OutputStreamReader의 인코딩을 알려준다. |
FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis, "KSC5601");
메서드명/생성자 | 설명 |
---|---|
RandomAccessFile(File file, String name) RandomAccessFile(String fileName, String mode) | 주어진 file에 읽기 또는 읽기와 쓰기를 하기 위한 RandomAccessFile 인스턴스를 생성한다. mode는 “r(읽기)”과 “rw(읽기/쓰기)” 두 가지 값이 지정 가능하다. |
long getFilePointer() | 파일 포인터의 위치를 알려준다. |
long length() | 파일의 크기를 byte 단위로 얻을 수 있다. |
void seek(long pos) | 파일 포인터의 위치를 변경한다. 위치는 파일의 첫 부분부터 pos 크기만큼이다. |
void setLength(long newLength) | 파일 크기를 byte단위로 지정된 길이로 변경한다. |
int skipBytes(int n) | 지정 수 만큼의 byte를 skip한다. |
예제와 파일 내용
static final String FILEPATH = "/testme.txt";
public static void main(String[] args){
try{
System.out.println(new String(readFromFile(FILEPATH, 0, 13)));
writeToFile(FILEPATH, "RandomAccessFile Read Write test file!!!", 14);
}catch(IOException e){
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RansomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
[결과]
Welcome!
test
[파일내용]
Welcome!
test
RandomAccessFile Read Write test file!!!
멤버변수 | 설명 |
---|---|
static String pathSeparator | 편의를 위해 문자열로 표시되는 시스템 종속 경로 구분 문자로 윈도우 “;”, 유닉스 “:” |
static char pathSeparatorChar | 시스템 종속 경로 구분 문자로 윈도우 “;”, 유닉스 “:” |
static String separator | 편의를 위해 문자열로 표시되는 시스템 종속 default-name 구분 문자 |
static char separatorChar | 시스템에 따라 달라지는 default-name 구분자로 윈도우 “;”, 유닉스 “:” |
메서드명/생성자 | 설명 |
---|---|
File(String fileName) | 지정한 문자열의 파일명을 갖는 파일을 핸들링할 수 있는 FIle 인스턴스를 생성한다. 파일 뿐만 아니라 디렉토리도 같은 방법으로 다룬다. |
File(String pathName, String fileName) | 파일의 경로와 이름을 따로 분리해서 지정할 수 있도록 한 생성자이다. |
String getName() | 파일이름을 문자열로 반환한다. |
String getPath() | 파일의 경로를 문자열로 반환한다. |
String getAbsolutePath() File getAbsolutePath() | 파일의 절대경로를 문자열로 반환한다. 파일의 절대경로를 File로 반환한다. |
String getParent() File getParentFile() | 파일의 상위 디렉토리를 문자열로 반환한다. 파일의 상위 디렉토리를 File로 반환한다. |
String getCanonicalPath() File getCanonicalFile() | 파일의 정규경로를 String으로 반환한다. |
파일의 정규경로를 File로 반환한다. | |
boolean canRead() | 파일을 읽을 수 있는지 여부를 체크한다. |
boolean canWrite() | 파일을 수정할 수 있는지 여부를 체크한다. |
boolean exists() | 파일이 존재하는지 체크한다. |
boolean isAbsolute() | 파일 또는 디렉토리가 절대경로명으로 지정되었는지 확인한다. |
boolean isDirectory() | 디렉토리인지 확인한다. |
boolean isFile() | 파일인지 확인한다. |
boolean isHidden() | 파일의 속성이 hidden 파일인지 확인한다. |
boolean createNewFile() | 내용이 없는 새로운 파일을 생성한다. 파일이 이미 존재하면 생성되지 않는다. |
static File createTempFile(String prefix, String suffix) | 임시파일을 시스템의 임스 디렉토리에 생성한다. |
String File createTempFile(String prefix, String suffix, File directory) | 임시파일을 시스템의 지정 디렉토리에 생성한다. |
boolean delete() | 파일을 삭제한다. |
void deleteOnExit() | 응용 프로그램 종료시 파일을 삭제한다. |
long length() | 파일의 크기를 반환한다. |
String[] list | 디렉토리의 파일목록을 String 배열로 반환한다. |
File[] listFiles() | 디렉토리의 파일목록을 File 배열로 반환한다. |
예제
try{
//새로운 파일 생성
File file =
new File("/NewFileEx02.txt");
file.createNewFile();
System.out.println(file);
//파일이 존재하는지 체크
boolean bool = file.exists();
//절대경로 반환
String path = file.getAbsolutePath();
if(bool){
System.out.println(path + " Exists? " + bool);
}
}catch(Exception e){
e.printStackTrace();
}
[결과]
/NewFileEx02.txt
/NewFileEx02.txt Exists? true
File targetFile = new File("/streamtest");
File[] files = targetFile.listFiles();
for(int i=0; i<files.length; i++){
File f = files[i];
String attribute = "";
attribute = f.getName();
if(files[i].isDirectory()){
attribute += " /Directory";
}else{
attribute += " / size : " + f.length() +
" / canRead : " + f.canRead() +
" / canWrite : " + f.canWrite() +
" / isHidden : " + f.isHidden();
}
System.out.println(attribute);
}
public interface Serializable{}
public class Member implements java.io.Serializable{
String name;
String password;
int age;
}
public class Member implements java.io.Serializable{
String name;
transient String password; //직렬화 대상 제외
int age;
}
public class Member implements java.io.Serializable{
String name;
transient String password; //직렬화 대상 제외
int age;
Object o = new Object(); //Object는 직렬화 제외
}
public class ParentMember{
String name; //직렬화 안 됨
String password; //직렬화 안 됨
}
public class Member extends ParentMember implements Serializable{
int age;
}
try{
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("/obj.txt"));
Member m = new Member("GilDong", "1234", 30);
oos.writeObject(m);
System.out.println("객체 저장 완료!");
oos.close();
System.out.println("저장된 객체 읽기!");
ObjectInputStream ois = new ObjectInputStream()
new FileInputStream("/obj.txt"));
Member im = (Member)ois.readObject();
System.out.println("이름: " + im.getName());
System.out.println("비밀번호: " + im.getPassword());
System.out.println("나이: " + im.getAge());
ois.close();
}catch(Exception e){
e.printStackTrace();
}
[결과]
객체 저장 완료!
저장된 객체 읽기!
이름: GilDong
비밀번호: 1234
나이: 30
ObjectInputStream(InputStream in)
ObjectOutputStream(OutputStream out)
FileOutputStream fos = new FileOutputStream("objectfile.ser");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(new UserInfo());
FileInputStream fos = new FileInputStream("objectfile.ser");
ObjectInputStream in = new ObjectInputStream(fos);
UserInfo info = (UserInfo)in.readObject();
ObjectOutputStream | ObjectInputStream |
---|---|
void defaultWriteObject() void write(byte[] buf) void write(byte[] buf, int off, int len) void write(int val) void writeBoolean(boolean val) void writeByte(int val) void writeBytes(String val) void writeChar(int val) void writeChars(String str) void writeDouble(double val) void writeFloat(float val) void writeInt(int val) void writeLong(long val) void writeObject(Object obj) void writeShort(int val) void writeUTF(String str) | void defaultReadObject() int read() int read(byte[] buf, int off, int len) boolean readBoolean() byte readByte() char readChar() double readDouble() float readFloat() int readInt() long readLong() short readShort() Object readObject() String readUTF() |
구분 | java.io | java.nio |
---|---|---|
입출력 방식 | 스트림 방식 | 채널 방식 |
비동기 방식 | 지원 안 함 | 지원 |
Buffer 방식 | Non-buffer | Buffer |
Blocking/non-blocking 지원 | Blocking only | Blocking/Non-blocking 모두 지원 |