IO
자바의 스트림은 문자 스트림과 바이트 스트림으로 구분할 수 있다.
문자스트림은 16비트단위로, 바이트 스트림은 8비트 단위로 데이터를 읽고,쓴다.
문자스트림은 메모장으로 읽을 수 있고, 바이트 스트림은 메모장으로 읽지 못한다.
문자스트림은 16비트 유니코드로 데이터를 입출력할 때 사용합니다.
- Writer추상클래스는 모든 문자 출력 스트림에 사용할 수 있는 기능을 정의하고 있다.
- OutputStreamWriter클래스는 특정 문자 인코딩 규칙에 따라 문자 스트림을 바이트 스트림으로 변환한다.
- FileWriter클래스는 OutputStreamWriter를 확장(상속)하고 문자를 파일에 출력합니다.
- 생성자
OutputStreamWriter(OutputStream os) throws IOException
=>특정문자 인코딩 규칙에 따라 문자스트림을 바이트 스트림으로 변환한다.
OutputStreamWriter(OutputStream os, String encording) throws IOException
=> os는 출력스트림이고 encording은 문자 인코딩 이름이다.
FileWriter(String filepath) throws IOException
=> filepath(파일경로)
FileWriter(String filepath, boolean addend) throws IOException
=> append가 true 이면 문자 파일 끝에 추가한다.
FileWriter(File fileObj)
=>fileObj는 그 파일을 나타내는 파일의 객체이다.
InputStreamReader(InputStream is) throws IOException
=> is는 입력스트림, encoding은 사용자 시스템에 설정된 기본문자 인코딩 적용
InputStreamReader(InputStreamis, String encoding) throws IOException
=> encoding은 문자 인코딩 이름
FileReader(String filepath)
=> filepath 파일 전체 경로 이름
FileReader(File fileObj)
=> 그 파일을 나타내는 File객체이다.
-메소드
void close() => 입출력 스트림 닫기
void flush() => 출력 스트림 내용을 비운다.
void write(int c) => 한 문자 쓰기 // int형 하위 2바이트
void write(char buffer[], int index, int size) => index위치부터 size만큼 스트림에 출력한다.
void write(String s) => 문자열 쓰기
void write(String s, int index, int size) =>index위치부터 size만큼 문자열 쓰기
int read() => 한 문자를 읽는다.
int read(char buffer[]) => 입력스트림에서 buffer배열로 문자를 읽어온다.
int read(char buffer[], int offset, int num) => 입력스트림에서 num 만큼 문자를 읽어 읽은 문자 개수 리턴
문자스트림 클래스 내부
Objcet - Reader - BufferedReader
InputStreamReader - FileReader
Writer - BufferedWriter
OutputStreamWriter - FileWriter
PrintWriter
바이트스트림 클래스 내부
Object - ImputStream - FileInputStream
FilerInputStream - BufferedInputStream
DataInputStream
- OutputStream - FileOutputStream
FilterOutputStream - BufferedOutputStream
DataOutputStream
PrintStream
public FileWriter(String fileName) throws IOException
Constructs a FileWriter object given a file name.
import java.io.*;
class FileW
{
public static void main(String args[])throws IOException
{
FileWriter fw = null;
try
{
fw = new FileWriter("a1.txt");// 객체생성
for(int i = 1; i<=5 ; i++)
{
fw.write("줄번호:" +i+"\n");//파일에 문자열 쓰기
}
fw.close();
}
catch(Exception e)
{
System.out.println("예외:" +e);
}
finally
{
try
{
if(fw != null)
{
fw.close();
}
}
catch(IOException ioe)
{
}
}
}
}
public FileReader(String fileName) throws FileNotFoundException
Creates a new FileReader, given the name of the file to read from.
import java.io.*;
class FileR
{
public static void main(String args[]) throws IOException
{
FileReader fr = new FileReader("a1.txt");
int a;
while((a =fr.read()) != -1) //파일 끝이 아닌 동안 반복
{
System.out.println((char)a);
}
fr.close();
}
}
import java.io.*;
{
public static void main(String args[]) throws IOException
{
try
{
//FileWriter fw = new FileWriter("b1.txt"); //파일쓰기 객체 생성
//BufferedWriter bw = new BufferedWriter(fw);
BufferedWriter bw = new BufferedWriter(new FileWriter("b1.txt"));
//파일에 문자열 쓰기
for(int i=1 ; i<=7; i++)
{
bw.write("줄번호: " +i+ "\n");
}
bw.close();
}
catch(Exception e)
{
}
finally
{
}
}
}
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
import java.io.*;
class BuffR
{
public static void main(String args[])
{
try
{
//FileReader fr = new FileReader("b1.txt"); //파일 읽기 객체 생성
//BufferedReader br = new BufferedReader(fr); //버퍼 읽기 객체 생성
BufferedReader br = new BufferedReader(new FileReader("b1.txt"));
String str;
while((str = br.readLine()) != null)// 파일 끝이 아닌 동안.
{
System.out.println(str);
}
br.close();
}
catch(Exception e)
{
}
finally
{
}
}
}
System.in 은 InputStream 객체이기 때문에 InputStreamReader의 생성자의 인수로 전달된다.
그런 다음 InputStreamReader 객체가 BufferedReader 생성자 인수로 전달된다.
import java.io.*;
class ReadConsole
{
public static void main( String [] args ) throws IOException
{
try
{
//InputStreamReader isr = new InputStreamReader(System.in); //입력스트림 읽기 객체 생성
//BufferedReader br = new BufferedReader(isr);// 버퍼 읽기 객체 생성
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String strKor, strEng;
int kor,eng,tot;
System.out.print("국어점수 입력: ");
strKor = br.readLine();
System.out.print("영어점수 입력: ");
strEng = br.readLine();
kor = Integer.parseInt(strKor);
eng = Integer.parseInt(strEng);
tot = kor + eng;
System.out.println("총점 :"+ tot);
br.close();
}
catch(Exception e)
{
}
finally
{
}
}// end main
}
public PrintWriter(OutputStream out)
Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.
This convenience constructor creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding.
/*
자바의 PrintWriter객체는 Object를 비롯한 모든 형식에 대해서 Print()와 Println()를 지원한다
*/
import java.io.*;
class PrintWriterEx
{
public static void main( String [] args )
{
try
{
PrintWriter pw = new PrintWriter(System.out);//객체생성
pw.println(true);
pw.println('A');
pw.println(100);
pw.println(12.4);
pw.println("호호호");
pw.close();
}
catch(Exception e)
{
}
finally
{
}
}// end main
}
public FileOutputStream(String name) throws FileNotFoundException
Creates an output file stream to write to the file with the specified name. A new
FileDescriptor
object is created to represent this file connection. import java.io.*;
class ByteW
{
public static void main( String [] args ) throws IOException
{
try
{
FileOutputStream fos = new FileOutputStream("c1.txt");
for(int i = 1 ;i<=10; i++)
{
fos.write(i);
}
fos.close();
}
catch(Exception e)
{
}
finally
{
}
}// end main
}
FileInputStream
public FileInputStream(String name)throws FileNotFoundException
Creates a
FileInputStream
by opening a connection to an actual file, the file named by the path name name
in the file system. A new FileDescriptor
object is created to represent this file connection.import java.io.*;
class ByteR
{
public static void main( String [] args )
{
try
{
FileInputStream fis = new FileInputStream("c1.txt"); //입력스트림 객체 생성
// 데이터를 읽어와 출력하기
int i;
while ((i = fis.read()) != -1) // 파일 끝이 아닌 동안
{
System.out.println(i + " ");
}
fis.close();
}
catch(Exception e)
{
}
finally
{
}
}// end main
}
The class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.
import java.io.*;
class ByteBuffW
{
public static void main(String args[])
{
try
{
//FileOutputStream fos = new FileOutputStream("d1.txt"); //파일 출력 스트림 객체 생성
//BufferedOutputStream bos = new BufferedOutputStream(fos); // 버퍼 출력 스트림 객제 생성
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d1.txt"));
for(int i = 1 ; i<=20; i++)
{
bos.write(i);
}
bos.close();
}
catch(Exception e)
{
}
finally
{
}
}
}
public BufferedInputStream(InputStream in)
Creates a
BufferedInputStream
and saves its argument, the input stream in
, for later use. An internal buffer array is created and stored in buf
.import java.io.*;
class ByteBuffR
{
public static void main( String [] args ) throws IOException
{
//FileInputStream fis = new FileInputStream("d1.txt"); //파일입력스트림 객체 생성
//BufferedInputStream bis = new BufferedInputStream(fis);//버퍼 입력 스트림 객체 생성
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("d1.txt"));
int i;
while((i = bis.read()) != -1)
{
System.out.print(i+ " ");
}
bis.close();
}// end main
}
A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.
DataIntputStream
A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
import java.io.*;
class DataOutputStreamEx
{
public static void main( String [] args ) throws IOException
{
try
{
//데이터 저장
DataOutputStream dos = new DataOutputStream(new FileOutputStream("e1.txt"));
dos.writeBoolean(true); //자료형 크기대로 읽는다.
dos.writeChar('A');
dos.writeByte(Byte.MAX_VALUE);
dos.writeInt(100);
dos.writeDouble(100.7);
dos.writeChars("kim\n");//\n 삽입해야 홍길동이 제대로 나온다.
dos.writeUTF("홍길동");
dos.close();
//데이터 읽기
DataInputStream dis = new DataInputStream(new FileInputStream("e1.txt"));
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
System.out.println(dis.readByte());
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readLine());
System.out.println(dis.readUTF()); //한글사용가능
}
catch(Exception e)
{
}
finally
{
}
}// end main
}