본문 바로가기
Java

API - IO( InputStream - OutPutStream)

by 임혁진 2023. 11. 29.

 

Stream은 두가지로 나뉜다.

byte기반 ,문자 기반 

 

=> 오직 문자만 보낸다

 

 

 

 

Byte기반

=> 그림 , 문자 등 모든 종류의 데이터

 

File -> FileInputStream

       -> FileOutputStream

 

 

OutPutStream의 주요 메소드

Write(byte b) - 출력 스트림으로 1바이트씩 보냄

Write(byte[] b) - 출력 스트으로 주어진 바이트 배열 b의 모든 바이트들을 보낸다 -> 속도가 더 빠름

 

OutputStream 예제

public class OutputStreamEx {

 

public static void main(String[] args) {

 

/*

* 1. 파일을 쓸때 사용하는 클래스는 FileOutputStream클래스 입니다.

* 2. 1byte기반으로 데이터를 씁니다.

* 3. OutputStream클래스를 상속받습니다.

* 4. io패키지에 있는 모든 클래스는 throws를 던지고 있기 때문에, 반드시 try-catch블록과 함께사용됨

*

*/

 

//OutputStream fos = new FileOutputStream(파일을 쓸 경로);

 

Scanner scan = new Scanner(System.in);

 

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\test.txt"; // 파일의 경로

 

FileOutputStream fos = null;

 

try {

fos = new FileOutputStream(path);

 

//문장을 입력받음

System.out.print("문장입력>");

String str = scan.nextLine();

 

byte[] arr = str.getBytes(); //문자열에 대한 아스키코드를 바이트배열에 담아줍

 

fos.write( arr ); //파일을 씀

 

 

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

fos.close();

} catch (Exception e2) {}

 

}

}

}

 

InputStream

=> byte 단위로 읽음

 

=> 사용법 : InputStream (추상)클래스를 이용해서 객체를 만들고 하위 클래스로 구현 , 글자는 영어만가능

 

InputStream의 주요 메소드

1. read(): 입력 스트림으로 부터 1byte를 읽고 읽은 byte를 리턴

2. read(byte[] b) : 입력 스트림으로부터 읽은 매개값으로 주어진 byte 배열에 저장하고 실제로 읽은 byte 수를 리턴

3. close() : 스트림을 닫는다.

더 이상 사용하지 않을 때 시스템 자원을 풀어준다.

 

public class InputStreamEx {

 

public static void main(String[] args) {

 

/*

* 1. 파일을 읽을 때 사용하는 클래스는 FileInputStream클래스 입니다.

* 2. 1byte기반으로 데이터를 읽어들입니다.

* 3. InputStream클래스를 상속 받고 있습니다.

*

*/

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\test.txt";

 

 

try {

FileInputStream fis = new FileInputStream(path);

 

//System.out.println( (char)fis.read() );

//read() - 한글자씩 읽음, 더이상 읽을게 없다면 -1반환

int result;

 

while( (result = fis.read()) != -1 ) {

System.out.println( (char)result );

}

 

fis.close();

 

} catch (Exception e) {

 

e.printStackTrace();

}

}

}

 

InputStream,OutputStream 의 예제 FileCopy

public class FileCopyEx {

 

public static void main(String[] args) {

 

//

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\hello.mp4"; //input

String copypath = "C:\\Users\\user\\Desktop\\course\\java\\upload\\copy\\copy.mp4"; //output

 

try {

FileInputStream fis = new FileInputStream(path); //읽을경로

FileOutputStream fos = new FileOutputStream(copypath); //나갈경로

 

 

//바이트 배열단위로 읽음

// byte[] arr = new byte[1000];

// fis.read(arr);

// System.out.println(Arrays.toString(arr) );

 

//읽은 바이트의 개수를 반환, 더이상 읽을게 없다면 -1반환

byte[] arr = new byte[1000];

int result;

while( (result = fis.read(arr) ) != -1 ) {

 

fos.write(arr, 0, result); //써내릴 배열, 시작값, 끝값

//System.out.println(Arrays.toString(arr) );

}

System.out.println("파일복사완료");

 

fis.close(); //클로즈 안하면 두번째 실행부터 문제됨

fos.close();

 

} catch (IOException e) {

e.printStackTrace();

}

}

}

 

문자 기반 스트림 클래스

=> Input/OutputStream 은 1바이트 단위로 한글(2byte)등 타 언어는 깨질 수 있음

 

=> 유니코드 입/출력 클래스는 Reader와 Writer라고 부른다.

 

Writer

=> 사용법: writer 추상 클래스를 이용해서 객체를 만들고 하위클래스로 구현시킴

=> 2byte 문자도 정상 처리 가능

 

Writer 주요 메소드(InputStream클래스와 거의 동일)

1. read(): 입력 스트림으로 부터 1byte를 읽고 읽은 byte를 리턴

2. read(byte[] b) : 입력 스트림으로부터 읽은 매개값으로 주어진 byte 배열에 저장하고 실제로 읽은 byte 수를 리턴

3. close() : 스트림을 닫는다

public class FileWriterEx {

 

public static void main(String[] args) {

 

/*

* 1. 문자(한글)를 써서 저장할 때 사용하는 클래스는 FileWriter클래스 입니다.

* 2. 2byte단위로 문자를 씁니다

* 3. Writer클래스를 상속받습니다.

* 4. 비디오 or 오디오 같은 파일을 쓰기에는 적합하지 않습니다.

*/

 

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\copy\\test2.txt";

 

try {

 

//FileWriter fw = new FileWriter(path);

FileWriter fw = new FileWriter(path, true); //기존파일에 내용을 추가함

 

String str = "아 쉬는시간이네?\n\r집에가고싶다"; // \r캐리지리턴

fw.write(str);

 

fw.close();

 

System.out.println("파일생성완료");

 

} catch (Exception e) {

e.printStackTrace();

}

}

}

 

 

Reader의 사용법

=> Reader 추상 클래스를 이용해서 객체 생성 -> 하위 클래스로 구현 

   - 2Byte 문자도 정상적으로 처리 가능

 

Reader의 주요 메소드(InputStream과 거의 동일)

Write(byte b) - 출력 스트림으로 1바이트씩 보냄

Write(byte[] b) - 출력 스트으로 주어진 바이트 배열 b의 모든 바이트들을 보낸다 -> 속도가 더 빠름

 

public class FileReaderEx {

 

public static void main(String[] args) {

 

/*

* 1. 2byte기반으로 파일을 읽어들이는 클래스 FileReader

* 2. 한글(문자) 형태의 파일데이터를 읽기에 적합합니다.

* 3. Reader클래스를 상속받습니다.

*/

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\copy\\test2.txt";

 

try {

 

FileReader fr = new FileReader(path);

 

String str = ""; //문자열합

int result;

while( (result = fr.read() ) != -1 ) { //한글자를 읽고, 더이상 읽을게 없다면 -1반환

//System.out.print( (char)result);

str += (char)result;

}

 

System.out.println(str);

 

fr.close();

 

} catch (Exception e) {

e.printStackTrace();

}

}

}

 

향상된(빠른 입출력 IO)

=>BufferedOutPutStream

public class BufferedOutputEx {

 

public static void main(String[] args) {

 

/*

* 1. Buffered가 붙은 클래스는 기존클래스들의 성능향상 스트림 입니다

* 2. BufferedOutputStream 이라고하면, OutputStream의 성능향상 스트림입니다.

* 3. 1바이트단위로 빠르게 씁니다.

*

*/

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\abc.txt";

 

 

try {

//FileOutputStream fos = new FileOutputStream(path);

//BufferedOutputStream bf = new BufferedOutputStream(fos);

 

BufferedOutputStream bf = new BufferedOutputStream( new FileOutputStream(path) );

 

String str = "hello world";

 

bf.write( str.getBytes() );

 

bf.close(); //close가 일어나면 자동으로 flush가 호출됩니다.

 

 

System.out.println("파일출력성공");

 

} catch (Exception e) {

e.printStackTrace();

}

}

}

 

=>BufferedInPutStream

public class BufferedInputEx {

 

public static void main(String[] args) {

 

/*

* 1. BufferedInputStream은 InputStream의 성능향상 스트림입니다.

* 2. 1바이트 단위로 빠르게 읽어들입니다

*

*/

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\abc.txt";

 

try {

 

//FileInputStream fis = new FileInputStream(path);

//BufferedInputStream bis = new BufferedInputStream( fis );

 

BufferedInputStream bis = new BufferedInputStream( new FileInputStream(path) );

 

int result;

while( (result = bis.read() ) != -1 ) {

 

System.out.println( (char)result );

}

 

bis.close(); //내부에 있는 FileInputStream도 자동으로 닫힘

 

} catch (Exception e) {

e.printStackTrace();

}

}

}

 

 

=>BufferedWriter

public class BufferedWriterEx {

 

public static void main(String[] args) {

 

/*

* 1. BufferedWriter는 Writer의 성능향상 스트림입니다.

* 2. 2단위로 빠르게 읽고씁니다

*/

 

Scanner scan = new Scanner(System.in);

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\def.txt";

 

try {

BufferedWriter bw = new BufferedWriter( new FileWriter(path) );

 

while(true) {

 

String str = scan.nextLine();

if(str.equals("그만")) break;

 

bw.write(str); //2byte단위로 씀

bw.flush(); //버퍼를 밀어냄

}

 

bw.close(); //close되면 flush가 호출됨

 

} catch (Exception e) {

e.printStackTrace();

}

}

}

 

BufferedReader

public class BufferedReaderEx {

 

public static void main(String[] args) {

 

/*

* 1. BufferedReader는 Reader클래스의 성능향상 보조 스트림입니다.

* 2. 2byte단위로 읽어들입니다.

*/

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\def.txt";

 

try {

 

BufferedReader br = new BufferedReader( new FileReader(path) );

 

//String str = br.readLine(); //한줄을 읽어들입니다.

//System.out.println(str);

 

String str;

while( (str = br.readLine()) != null ) {

 

System.out.println(str);

}

 

br.close();

 

} catch (Exception e) {

e.printStackTrace();

}

}

}

 

Buffered 

=>Scanner는 편의를 위해서 만들어진 클래스

//System.out.println도 편의를 위해서 만들어진 메소드

 

public class 빠른입출력 {

 

public static void main(String[] args) {

 

//Scanner는 편의를 위해서 만들어진 클래스.

//System.out.println도 편의 위해서 만들어진 메서드.

 

 

 

try {

 

 

//빠른입력

//Reader r = new InputStreamReader(System.in);

//BufferedReader br = new BufferedReader( r );

 

BufferedReader br = new BufferedReader( new InputStreamReader(System.in));

System.out.println(br.readLine());

 

//빠른출력

Writer w = new OutputStreamWriter( System.out ); //콘솔로의 출력

BufferedWriter bw = new BufferedWriter( w );

 

bw.write("내가하고싶은말....");

bw.flush();

 

//클로즈

br.close();

bw.close();

 

 

} catch (Exception e) {

e.printStackTrace();

}

}

}

 

BufferedEncoding 

=> 인코딩 - 인간의 문자데이터를 컴퓨터가 아는 문자형태로 표현하는 것

public class BufferedEncoding {

 

public static void main(String[] args) {

 

//인코딩 - 인간이 사용하는 문자데이터를 컴퓨터가 아는 문자형태로 표현하는 것

//한글은 인코딩타입이 맞지 않으면, 전부 깨지는현상이 발생함.

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\encoding.txt";

 

 

try {

 

//인코딩을 지정해서 파일을 읽어 들이는 방법(일시적)

FileInputStream fis = new FileInputStream(path);

InputStreamReader isr = new InputStreamReader(fis, "EUC-KR");

BufferedReader br = new BufferedReader(isr);

 

String str;

while( (str = br.readLine()) != null ) {

System.out.println(str);

}

 

br.close(); //

 

} catch (Exception e) {

e.printStackTrace();

}

}

}

 

이클립스로 폴더 생성하고 삭제하기

=> 폴더 만들기

: File 객체를 사용

-> .mkdirs();

-> .exists() ; 폴더가 존재하는지

 

public class CreateFolderEx {

 

 

public static void main(String[] args) {

 

/*

* 자바에서 외부경로로 폴더(파일)를 확인하거나 or 폴더(파일)를 생성하거나 or 폴더(파일)를 삭제 할수있습니다.

* File객체를 사용합니다.

*/

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\hello";

 

try {

File file = new File(path);

 

//폴더(파일) 존재하는지 확인하는 메서드 exist

 

if( file.exists() ) { //존재하면 true, 없다면 false

System.out.println("폴더가 존재합니다");

} else {

file.mkdirs(); //폴더 생성

System.out.println("폴더가 존재하지 않습니다");

}

 

 

 

} catch (Exception e) {

e.printStackTrace();

}

}

}

 

폴더(파일) 삭제하기

File 객체를 사용

.delete() 로 삭제 ** 폴더 안이 비어 있어야한다.

public class DeleteFolderEx {

 

public static void main(String[] args) {

 

 

String path = "C:\\Users\\user\\Desktop\\course\\java\\upload\\hello";

 

 

try {

 

File file = new File(path);

 

if(file.exists() ) {

file.delete(); //폴더(폴더안에 empty해야 합니다) or 파일의 삭제

System.out.println("폴더 삭제완료");

}

 

 

 

} catch (Exception e) {

e.printStackTrace();

}

 

 

}

}