자바 입출력은 크게 표준 입출력과 파일 입출력으로 나눌수 있으며, 표준 입출력은 키보드로부터 입력을 받고 모니터로 출력하는 것을 말한다. 파일 입출력은 파일로부터 데이터를 입력받아서 다시 파일로 출력하는것을 말한다, 물론 키보드로 입력받고 파일로 출력할 수도 있고, 파일로부터 받은 입력을 모니터로 출력할수 있다.
스트림은 데이터가 다니는 길을 말한다. 스트림은 컴퓨너톼 입출력 장치 사이에 연결된 길이고, 이러한 스트림에 적절한 입출력 클래스를 이용해서 데이터를 읽어 들이거나 출력하게 되는 것, 스트림은 크게 바이트 스트림과 문자 스트림으로 구분되며, 이름 그대로 바이트 스트림은 바이트 단위로 데이터 입출력이 이루어지고, 문자 스트림은 문자 단위로 입출력이 이루어진다. 자바의 초기 버전에서는 바이트 스트림만 있엇지만 버전이 업그레이드되면서 문자 스트림이 추가됬다. 스트림 클래스의이름을 보면 데이터를 읽어 오기 위한 스트림인지, 아니면 데이터를 쓰기 위한 스트림인지를 알수가 있다.
또한 클래스명이 Stream으로 끝나면 바이트 단위로 입출력이 이루어지는 클래스이고 Reader/Writer로 끝나면 문자 단위로 데이터 입출력이 이루어진다.
자바에서는 스트림 중에 직접 데이터를 읽고 쓰는데 이용하는 스트림이 있고, 다른 스트림에 보조 역할을 하는 스트림이 있다. 보조역할을 하는 스트림은 직접 데이터를 읽고 쓰는 기능은 없다.
Object
위 구조에서 File 클래스는 파일로부터 데이터를 읽어 오거나 파일로 데이터를 저장할때 필요함
Object
InputStream
OutputStream
Object
Reader
Writer
표준 입력은 키보드로부터 데이터를 입력받는 것을 말하며, 주로 Scanner 클래스를 이용했으나 Scanner클래스를 정리하고 System 클래스를 이용해서 표준 입력 처리하는것을 실습해보자
스캐너 클래스는 표준 입력 처리에 유용하다. java.util패키지에 있으며, 다양한 자료형을 읽어올 수 있는 메소드들이 이어 다양한 데이터 입출력을 처리하는데 유용하다, 생성자는 여러가지가 있고 주로 사용되는 생성자는 다음이다.
[생성자]
| 생성자 | 설명 |
|---|---|
| Scanner(File source) | 파일 객체로부터 Scanner객체를 생성 |
| Scanner(InputStream source) | InputStream 객체로부터 Scanner객체를 생성 |
[메소드]
| 메소드 | 설명 |
|---|---|
| void close() | Scanner 객체를 닫음. |
| String next() | 문자열 데이터를 읽음. |
| boolean nextBoolean() | boolean 데이터를 읽음 |
| byte nextByte() | byte 데이터를 읽음 |
| short nextShort() | short 데이터를 읽음 |
| int nextInt() | Int 데이터를 읽음 |
| long nextLong() | long 데이터를 읽음 |
| float nextFloat() | float 데이터를 읽음 |
| double nextDouble() | double 데이터를 읽음 |
import java.util.Scanner;
Scanner scin = new Scanner(System.in);
String x = scin.next();
int y = scin.nextInt();
double z = scin.nextDouble();
scin.close();
표의 메소드들을 이용하는 예제를 보자.
package javainputouput.scanner;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args){
Scanner scin = new Scanner(System.in);//System.in -> 키보드를 말함
System.out.print("Name : ");
String name = scin.next(); //string을 읽을떄
System.out.print("Phone number: ");
String phone = scin.next();
System.out.print("Age: ");
int age = scin.nextInt();//read int
System.out.print("Height : ");
float height = scin.nextFloat(); //read float
System.out.print("Gender : ");
char gender = scin.next().charAt(0);//string 첫문자
System.out.println("Name : " + name);
System.out.println("Phone: " + phone);
System.out.println("Age : " + age);
System.out.println("height: " + height);
System.out.println("Gender: " + gender);
scin.close();
}
}
Name : alice
Phone number: 010
Age: 13
Height : 150.3
Gender : femail
Name : alice
Phone: 010
Age : 13
height: 150.3
Gender: f
인스턴스 생성후 입력받을 프린트 와 스트링을 입력받을수 있는 next()나 int() flort()를 써서 입력받는다.
System 클래스를 이용해서 키보드로부터 데이터를 읽어들이는 방법을 알아보자, System 클래스는 다음과 같이 in, out, err 필드를 가지고 있으며, 우리가 사용했던 System.in , System.out 이 이에 해당된다
[필드]
필드인 in 이 InputStream 타입이기 때문에 InputStream 클래스에 있는 메소드들을 사용할수가 있다. InputStream 메소드들은 다음과 같다
read()메소드를 이용해 하나의 문자를 입력 받는 코드를 봐보자
package javainputouput.system;
import java.io.IOException;
public class Test1 {
public static void main(String[] args){
System.out.print("Enter one character: ");//print()는 입력받을떄
int x;
try{
x = System.in.read();
System.out.println("You entered " + x);
System.out.println("You entered " + ((char)x));//read() 메소드 반환값을 int이며 char로 형변환 해야 영문자출력됨
}catch(IOException e){
e.printStackTrace();
}
}
}
Enter one character: a
You entered 97
You entered a
out PrintStream 타입이기 떄문에 printStream 클래스의 메소드들을 사용할 수가 있다. PrintStream 클래스에는 다음과 같이 write()와 print()메소드가 있습니다.
[write 메소드]
| 메소드 | 설명 |
|---|---|
| public abstract void write(int b) | 정수 b의 하위 8비트 출력 |
| public void write(byte[] b)throws IOException | byte 배열 b의 내용을 출력함 |
| public void write(byte[] b, int off, int len)throws IOException | 배열 b의 off위치부터 len길이 만큼 출력 |
파일로부터 데이터를 읽어 오는 클래스는 FileInputStream과 FileReader 클래스가 있으며, 그리고 파일에 데이터를 저장(출력)하는 클래스는 FileOutputStream 과 FileWriter 클래스가 있다 . 따라서 다음과 같이 정리할수 있다.
[파일 입력 클래스]
[파일 출력 클래스]
파일생성후 텍스트 파일 을 만들고 데이터를 생성한다
filesave(폴더) 안데 data.text -> 데이터 입력
파일로부터 데이터를 읽어 오려면 프로그램과 파일 사이에 스트림 객체를 만들어야한다. 그떄 사용하는것이 FileInputStream 클래스 이며, FileInputStream 클래스의 생성자를 통해서 프로그램과 파일 사이에 스트림 객체를 만들수 있습니다.
[FileInputStream 생성자]
| 생성자 | 설명 |
|---|---|
| FileInputStream(File file) | File 객체로부터 스트림 객체를 생성함 |
| FileInputStream(String name) | 파일명을 이용하여 스트림 객체를 생성함 |
두 생성자는 실제로 다음과 같다 , 반드시 FileNotFoundException에 대한 예외 처리를 해야한다.
[FileInputStream 메소드]
| 메소드 | 설명 |
|---|---|
| int read() | 입력 스트림으로부터 1바이트 데이터를 읽고, 읽은 데이터 바이트 수를 반환 |
| int read(byte[] b) | 입력 스트림으로부터 여러 바이트의 데이터를 읽어서 바이트 배열 b에 저장하고 읽은 데이터의 바이트 수를 반환 |
| int read(byte[] b, int off,int len | 입력 스트림으로부터 len 길이의 데이터를 읽어서 바이트배열 b[off] 위치로부터 저장하고 읽은 데이터의 바이트 수를 반환 |
스트림을 이용한 데이터 읽기가 끝났으면 스트림을 닫아 주어야한다. 이때 사용하는것이 close()메소드이며, 위의 생성자와 메소드들을 이용하여 파일에서 데이터를 읽어 올수있다.
-public int read()throws IOException
-public int read(byte[] b)throws IOException
-public int read(byte[] b, int off, int len)throws IOException
생성자를 이용하여 filesavetests.text파일과 프로그램을 연결한 후에 파일로부터 데이터를 읽어오는 예제
package filesavetest;
import java.io.FileInputStream;//파일객체로부터 스트림 객체를 생성함
import java.io.IOException;
public class Test1 {
public static void main(String[] args)
{
FileInputStream fis = null;
try {
fis = new FileInputStream("/Users/iyeong-gwang/Desktop/Java/hello/src/filesavetest/filesavetests.txt");
System.out.println((char)fis.read( ));
System.out.println((char)fis.read( ));
System.out.println((char)fis.read( ));
System.out.println((char)fis.read( ));
System.out.println((char)fis.read( ));
System.out.println((char)fis.read( ));
System.out.println((char)fis.read( ));
System.out.println((char)fis.read( ));
}
catch(IOException e) {
System.out.println(e);
}
finally {
try {
fis.close( );
}
catch (IOException e) {
System.out.println(e);
}
}
System.out.println("main end");
}
}
h
e
l
l
o
w
o
main end
한자씩 불러오고 있다.
처음부터 끝까지 읽어 오려면?
반복문 사용
package filesavetest;
import java.io.FileInputStream;
import java.io.IOException;
public class Test2 {
public static void main(String[] args){
FileInputStream fis = null;
String a = "/Users/iyeong-gwang/Desktop/Java/hello/src/filesavetest/filesavetests.txt";
try{
fis = new FileInputStream(a);
int x;
while((x = fis.read()) != -1){
System.out.print((char)x);
}
}catch(IOException e){
System.out.println(e);
}finally{
try{
fis.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
}
hello world
java
//파일데이터를 모두 읽어왔다면 close()메소드를 넣어서 프로그램과 파일간의 스트림을 닫는것이 좋다.
없는 파일을 입력한다면?
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.FileInputStream.close()" because "fis" is null
null이라 close를 호출할수 없다.
따로 예외처리를 해줘야한다
package filesavetest;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
public class Test2 {
public static void main(String[] args){
FileInputStream fis = null;
String a = "/Users/iyeong-gwang/Desktop/Java/hello/src/filesavetest/filesavetests2.txt";
try{
fis = new FileInputStream(a);
int x;
while((x = fis.read()) != -1){
System.out.print((char)x);
}
} catch(FileNotFoundException e){
System.out.println("xxxx.txt는 없는 파일입니다.");
}
catch(IOException e){
System.out.println(e);
}finally{
try{
fis.close();
}
catch(IOException e){
System.out.println(e);
}
catch(NullPointerException e){
System.out.println("fis 가 null값을 가지고있다");
}
}
}
}
xxxx.txt는 없는 파일입니다.
fis 가 null값을 가지고있다
try{
파일 스트림 연결하기
파일에서 데이터 읽어오기
}
catch(FileNotFoundException e){
파일일 잘못입력했을때 예외 처리
}
catch(IOException e){
읽은 파일 나타내기
}
finally{
try{
스트림닫기
}
catch(IOException e){
System.out.println(e)
}
catch(NullPointerException e){
null 값일때
}
}
//현재 코드에서 보면 close메소드가 예외처리를 발생시키기 떄문에 코드에서 예외처리가 많아졌다. 이 부분을 효율적으로 처리하기 위해 자바7 에서는 AutoClosealbe 인터페이스를 추가하고 try with resouces라는 개념을 추가하였다.
package filesavetest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Test5 {
public static void main(String[] args){
FileInputStream fis = null;
byte b[] = new byte[50];
try{
fis = new FileInputStream("/Users/iyeong-gwang/Desktop/Java/hello/src/filesavetest/filesavetests.txt");
fis.read(b);
for(byte x : b)
System.out.print((char)x);
// System.out.println()으로 할시에는 한글자식 엔터가 들어간다
}
catch(FileNotFoundException e){
System.out.println("filesavetest는 없는 파일입니다");
}catch(IOException e){
System.out.println(e);
}
finally{
try{
fis.close();
}
catch(IOException e){
System.out.println(e);
}
catch(NullPointerException e){
System.out.println("fis가 null 값을 갖고 있습니다");
}
}
}
}
hello world
java
현재 까지는 파일명을 이용해서 스트림을 만들었고, 이번에는 File 클래스를 이용하여 FileInputStream 객체를 만들자
package filesavetest;
import java.io.*;
public class Test6 {
public static void main(String[] args){
File file = new File("/Users/iyeong-gwang/Desktop/Java/hello/src/filesavetest/filesavetests.txt");
FileInputStream fis = null;
try{
fis = new FileInputStream(file);
int x;
while((x = fis.read()) != -1){
System.out.print((char)x);
}
}
catch(IOException e){
System.out.println(e);
}
finally{
try{
fis.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
}
hello world
java
[FileReader 생성자]
| 생성자 | 설명 |
|---|---|
| FileReader(File file) | File 객체를 통하여 FileReader 객체를 생성함 |
| FileReader(String fileName) | 파일명을 이용하여 FileReader 객체를 생성함 |
[FileRead 메소드]
| 메소드 | 설명 |
|---|---|
| int read() | 파일로부터 한 문자를 읽어오고, 읽어온 데이터를 반영함 |
| int read(char[] cbuf | 파일로부터 읽어온 문자들을 배열 cbuf에 저장함 |
| int read(char[] cbuf, int offset,int length) | 파일로부터 length개의 문자를 읽어와서 배열 cbuf[offset 위치부터 저장함] |
package filesavetest;
import java.io.FileReader;
import java.io.IOException;
public class Test7 {
public static void main(String[] args){
FileReader fis = null;
try{
fis = new FileReader("/Users/iyeong-gwang/Desktop/Java/hello/src/filesavetest/filesavetests.txt");
int x;
while((x = fis.read()) != -1){
System.out.print((char)x);
}
}catch(IOException e){
System.out.println(e);
}
finally{
try {
fis.close();
}catch(IOException e){
System.out.println(e);
}
}
}
}
package filesavetest;
import java.io.FileReader;
import java.io.IOException;
public class Test8 {
public static void main(String[] args){
FileReader fis = null;
char data[] = new char[25];
try{
fis = new FileReader("/Users/iyeong-gwang/Desktop/Java/hello/src/filesavetest/filesavetests.txt");
fis.read(data);
for(int x : data)
System.out.print((char)x);
}catch(IOException e){
System.out.println(e);
}finally{
try{
fis.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
}
배열 갯수만 큼 반복문으로 넣음
System.in을 생성자로 넣고 키보드로부터 데이터를 읽어 들일 때 주로 사용했었다. Scanner 클래스의 생성자 중에 파일을 입력받는 생성자를 이용하면 파일 처리를 할수 있다.
기본형태
Scanner scin = new Scanner(new file(파일명));
while(sc.hasNext()){
//파일에서 다음 데이터 읽어오기;
}
기본형태에서 보듯이 Scanner클래스에는 다음에 읽을 데이터가 있는지를 판단하는 메소드가 있다.
Scanner 메소드 정리
| 메소드 | 설명 |
|---|---|
| public boolean hasNext() | 다음에 읽어올 토큰이 있는지 판단, 읽어올 토큰이 있으면 true or false |
| public String next() | 다음 문자열을 읽어옴 |
| public boolean nextBoolean() | 다음 토큰을 읽어서 boolean으로 반환함 |
| public byte nextByte() | 다음 토큰을 읽어서 byte로 반환함 |
| public short nextShort() | 다음토큰을 읽어서 short로 반환함 |
| public int nextInt() | 다음 토큰을 읽어서 int로 반환 |
| public long nextLong() | 다음 토큰을 읽어서 long으로 반환함 |
| public float nextFloat() | 다음 토큰을 읽어서 float로 반환함 |
| public double nextDouble() | 다음 토큰을 일겅서 double로 반환함 |
파일에
hello 10 true 5.3
1000000000
7 50 123.1234
위와 같이 데이터가 저장되어 있을때 Scanner를 이용해 파일 입력처리를 해보자
package scannerclass;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args){
File file = new File("hello/src/scannerclass/scannertext.txt");
Scanner scin = null;
String a= "";
short b = 0;
boolean c = false;
float d = 0.0f;
long e = 0;
byte f = 0;
int g = 0;
double h = 0.0;
if(file.exists()){
try{
scin = new Scanner(file);
a = scin.next();
b = scin.nextShort();
c = scin.nextBoolean();
d = scin.nextFloat();
e = scin.nextLong();
f = scin.nextByte();
g = scin.nextInt();
h = scin.nextDouble();
}
catch(FileNotFoundException exp){
System.out.println(exp);
}
}
System.out.println("a: " + a);
System.out.println("b: " + b);
System.out.println("c: " + c);
System.out.println("d: " + d);
System.out.println("e: " + e);
System.out.println("f: " + f);
System.out.println("g: " + g);
System.out.println("h: " + h);
}
//알아서 걸러준다 신기해
}
학생들의 정보가 있을때 각 학생을 객체로 생성하여 객체 배열에 저장하는 클래스를 작성해보자
1 David 80
2 Andrew 92
3 Cindy 88
4 paul 82
5 Tom 73
6 Alice 85
7 Elizabeth 79
8 Daniel 100
9 Sarah 81
10 Jennifer 95
package scannerclass;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
class Student{
private int no;
private String name;
private int score;
Student(){}
Student(int no, String name, int score){
this.no = no;
this.name = name;
this.score = score;
}
int getNo(){return no;}
String getName(){return name;}
int getScore(){return score;}
public String toString(){
return no + " :" + name +"(" + score + ")";
}
}
public class Test2 {
public static void main(String[] args){
Student ST[] = new Student[10];
File file = new File("hello/src/scannerclass/student.txt");
Scanner scin = null;
int i = 0;
try{
scin = new Scanner(file);
while(scin.hasNext()){
int no = scin.nextInt();
String name = scin.next();
int score = scin.nextInt();
ST[i++] = new Student(no,name,score);
}
}catch(IOException e){
System.out.println("student.txt not exist!!");
}
System.out.println("== Student List ==");
System.out.println("------------------");
for(Student s : ST){
System.out.println(s);
}
scin.close();
}
}
/**
* toString 메소드는 자바에서 특별히 취급하는 메소드이다. toString을 직접 호출하지 않아도 어떤 객체를 System.out.print로 호출
* 을 한다면 toString()이 호출되도록 약속되어있다.
* - 생코 -
*/
파일 출력은 파일로 데이터를 저장하는 것을 말한다. 바이트 스트림의 데이터를 저장할 때는 FileOutputStream 을 이용하고 문자 단위의 데이터를 저장할 떄 는 FileWriter 클래스를 사용한다.
[FileOutputStream 생성자 ]
| 생성자 | 설명 |
|---|---|
| FileOutputStream(File file) | File 객체로부터 스트림을 생성함 |
| FileOutputStream(File file,boolean append) | File 객체로부터 스트림을 생성하는데, 이미 존재하는 파일이면 원래 내용 밑에 추가하는지를 append에 제공함. |
| FileOutputStream(String name | 문자열로 파일명을 입력받아 스트림을 생성함 |
| FileOutputStream(String name, boolean append | 문자열 객체로부터 스트림을 생성하는데, 이미 존재하는 파일이면 원래 내용 밑에 추가하는지를 append에 제공함 |
//()안에 오버라이딩해서 넣는것
[FileOutputStream 메소드]
| 메소드 | 설명 |
|---|---|
| void close() | 스트림닫음 |
| void flush() | 출력 버퍼를 강제로 비우고 데이터 출력 |
| abstract void write(int b) | 데이터 b를 파일로 출력함 |
| void write(byte[] b | b 바이트 길이의 테이터를 파일로 출력함 |
| void write(byte[] b, int off, int len | 배열 b[off]부터 len길이 만큼의 데이터를 파일로 출력 |
package ouputstream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 {
public static void main(String[] args){
String content = "Hello java Programmers";
byte[] bytes = content.getBytes();
FileOutputStream fos = null;
try{
fos = new FileOutputStream("data321.text");
fos.write(bytes);
}catch(IOException e){
e.printStackTrace();
}finally{
try{
fos.close();
}catch(IOException e){
System.out.println(e);
}
}
}
}
data321.text 가 생겻고 그안에 Hello java programmers가 생겼다
파일로부터 데이터를 읽어 들일 때는 파일이 존재해야하며, 만약에 없는 파일에서 데이터를 읽으려고 한다면 FileNotFoundException이 발생한다 하지만 파일로 데이터를 저장할때는 없는 파일이면 새로 생성된다.
생성자 FileOutputStream(String name, boolean append)에서 append 매개변수에 true를 넣으면 기존에 내용이 있는 파일에 새로운 데이터를 저장하는 경우, 기존 내용 뒤에 새로운 내용을 덧붙인다. append 매개변수에 false를 넣으면 기존 내용은 모두 지우고 새로운 내용을 기존 내용위에 덮어 쓴다.
ex
fos = new FileOutputStream("data321.text",true); 할경우 똑같은 메세지를 뒤에 append한다
[FileWrite 생성자]
| 생성자 | 설명 |
|---|---|
| FileWriter(File file) | File 객체로부터 스트림을 생성함 |
| FileWriter(File file, boolean append | File 객체로부터 스트림을 생성하는데, 이미 존재하는 파일이면 원래 내용 밑에 추가하는지를 append에 제공함 |
| FileWriter(String fileName) | 문자열로 파일명을 입력받아 스트림을 생성함 |
| FileWriter(String fileName,boolean append) | 문자열 객체로부터 스트림을 생성하는데, 이미 존재하는 파일이면 원래 내용 밑에 추가하는지를 append에 제공함 |
[FileWriter 메소드]
| 메소드 | 설명 |
|---|---|
| void write(char[] cbuf | 문자배열 cbuf의 내용을 파일에 출력함 |
| void write(String str) | 문자열 str을 파일에 출력함 |
| void write(char[] cbuf,int off, int len | 문자배열 cbuf[off]부터 len개 문자를 파일에 출력함 |
| void write(String str, int off, int len) | 문자열 str[off] 부터 len 개 문자를 파일에 출력함 |
파일출력
package filewriter;
import java.io.FileWriter;
import java.io.IOException;
public class Test1 {
public static void main(String[] args){
char[] cbuf = {'J','A','V','A'};
String lang = "Language";
FileWriter fos = null;
try{
fos = new FileWriter("data5.txt");
fos.write(cbuf);
fos.write("₩n.....");
fos.write(lang);
}
catch(IOException e){
e.printStackTrace();
}
finally{
try{
fos.close();
}catch (IOException e){
System.out.println(e);
}
}
}
}
data5.txt => JAVA₩n.....Language 파일 생성
보조 스트림 클래스는 파일로부터 직접 데이터를 읽어 오고나, 파일에 직접 데이터를 저장할 수 있는 기능이 없다. 이름대로 다른 스트림에 보조적으로 적용할 수 있는 클래스이며, 주로 사용하는 보조스트림 입력을 알아보자.
보조스트림 클래스는 입출력 성능 향상을 위해 제공되는 클래스로 다음과 같은 클래스들이 있다
InputStreamReader/ OutputStreamWriter
BufferedInputStream/ BufferedOutputStream
BufferedReader / BufferedWriter
이 두 스트림 클래스는 바이트 스트림을 문자로 변환해 주는 클래스
InputStreamReader
InputStreamReader 의 생성자를 살펴보자 보조스트림 클래스는 생성자가 특별하다
[InputStreamReader 생성자]
| 생성자 | 설명 |
|---|---|
| InputStreamReader(InputStream in) | InputStream 객체를 받아서 Reader 객체를 생성 |
| InputStreamReader(InputStream in, String charsetName | InputStream과 문자열을 입력 받아서 Reader 객체를 생성함 |
| InputStreamReader(InputStream in,Charset cs) | InputStream과 Charset 객체를 받아서 Reader 객체를 생성함 |
| InputStreamReader(InputStrema in,CharsetDecoder dec) | InputStream과 CharsetDecoder 객체를 받아서 Reader 객체를 생성 |
[InputStreamReader 메소드]
| 메소드 | 설명 |
|---|---|
| int read() | 문자 한개를 읽어옴. |
| int read(char[] cbuf,int offset,int length) | 파일에서 데이터를 읽어서 cbuf[offset] 배열에 length 만큼 저장함 |
[예제]
package inputstreamreaderandoutput;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test1 {
public static void main(String[] args){
FileInputStream fis = null;
InputStreamReader reader = null;
try{
fis = new FileInputStream("data6.txt");
reader = new InputStreamReader(fis);
int x;
while((x=reader.read()) != -1){
System.out.print((char)x);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
fis.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
}
//파일을 읽기 위해 파일인펏스트림으로 가져온후 미들웨어
//InputStremReader로 char형태로 변환하는 미들웨어연결
//글자를 읽음
java.io.InputStreamReader/ OutputStreamWriter - 파일 내용 출력
파일의 내용을 문자로 읽어서 문자로 화면에 출력하는 방법이다. InputStream/OutStream 클래스의 경우는 byte 단위의 읽기와 쓰기에 사용된다. 여기서 문제는 Java의 Char 와 String의 타입의 경우 Characters로 취급 되어진다. 이말은 Char / String를 저장하려면 char 단위로 읽고 쓰는 Reader 와 Writer를 사용해야 한다. Java는 이 문제를 해결하기 위해서 byte 단위로 데이터를 읽어 Char형태로 변화 시켜 연결 고리 역활을 하는 Object를 만들어 놓았다. 그 것이 InputStreamReader 와 OutputStreamWriter 이다.
출처: https://dev.umejintan.com/14 [피곤한 개발자의 하루]
//미들웨어같은건가?
[OutputStreamWriter 생성자]
| 생성자 | 설명 |
|---|---|
| OutputStreamWriter(OutputStream out) | OutputStream 객체를 받아서 Reader 객체를 생성 |
| OutputStreamWriter(OutputStream out,String charsetName) | InputStream과 문자열을 입력받아서 Reader객체를 생성 |
| OutputStreamWriter(OutputStream out, Charset cs) | InputStream과 Charset객체를 받아서 Reader 객체를 생성 |
| OutputStreamWriter(OutputStream out,CharsetEncoder enc) | InputStream과 CharsetDecoder 객체를 받아서 Reader 객체를 생성함 |
[OutputStreamWriter 메소드]
| 메소드 | 설명 |
|---|---|
| void write(char[] cbuf, int off, int len) | 문자배열 cbuf[off]로 부터 len개의 문자를 저장함 |
| void write(int c) | 문자 한 개를 저장함 |
| void write(String str, in off, int len | 문자열 str[off]로 부터 len개의 문자를 저장함 |
BufferedInputStream과 BufferedOutputStream은 입출력을 실행할 때 버퍼링 기능을 이용하여 좀더 빠르게 입출력이 이루어질 수 있도록 합니다 두 클래스 모두 stream으로 끝나기 때문에 바이트 단위로 입출력된다는 것을 알수 있다 BufferedInputStream 클래스의 생성자를 살펴보고 예제를 보자
[BufferedInputStream 생성자]
| 생성자 | 설명 |
|---|---|
| BufferedInputStream(InputStream in) | InputStream 객체를 받아서 BufferedInputStream객체를 생성함 |
| BuffredInputStream(InputStream in,int Size) | InputStream 객체와 버퍼 크기를 입력받아서 BufferedInputStream 객체를 생성함 |
BufferedInputStream 을 이용해 파일로부터 데이터를 읽어와서 출력해보자 파일에는 영문과 한글이 같이 저장되어있다 Stream 클래스를 이용했기 때문에 한글이 꺠지는 것을 볼수 있다. 이문제는 BufferReader로 해결할수 있다
package inputstreamreaderandoutput;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class Test2 {
public static void main(String[] args){
BufferedInputStream bis = null;
try{
bis = new BufferedInputStream(new FileInputStream("data6.txt"));
int x = 0;
while((x=bis.read()) != -1){
System.out.print((char)x);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
bis.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
}
java programming
ìë
í
¸ì%
한글이 깨진다 이문제는 BufferReader, BufferedWriter로 해결할수 있다
BufferedReader와 BufferedWriter 클래스도 이불력 시에 버퍼링 기능을 이용하고, Reader/Writer 클래스이기 때문에 문자 단위로 입출력이 이루어짐을 알 수가 있습니다. BufferedReader 클래스의 생성자와 메소드를 알아보자
[BufferedReader(Reader in)]
| 생성자 | 설명 |
|---|---|
| BufferedReader(Reader in) | Reader 객체를 이용해 BufferedReader 객체를 생성 |
| BufferedReader(Reader in, int sz) | Reader 객체와 버퍼 크기를 입력받아서 BufferedReader객체를 생성함 |
package inputstreamreaderandoutput;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test3 {
public static void main(String[] args){
BufferedReader reader = null;
try{
reader = new BufferedReader(new InputStreamReader(new FileInputStream("data6.txt")));
int x = 0 ;
while((x=reader.read()) != -1){
System.out.print((char)x);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
reader.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
}
java programming
안녕하세요% 미들웨어나 콜백함수같이 끼워넣는 형식으로
잘 해결되었다.
정리 InputStreamReader 는 형변환으로 사용하며 인자로 파일 인펏 스트림은 파일을 읽어오는것 읽어온 파일을 알맞게 형변환하고 한글깨짐현상을 버퍼로 고쳤다.
DataInputStream 클래스의 생성자는 한개 있다
[DataInputStream 생성자]
| 생성자 | 설명 |
|---|---|
| DataInputStream(InputStream in) | InputStream 객체를 이용하여 DataInputStream 객체를 생성함 |
[DataInputStream 메소드]
| 메소드 | 설명 |
|---|---|
| input read(byte[] b | 데이터를 읽어 바이트 배열 b에 저장함. |
| int read(byte[] b, int off, int len) | 데이터를 읽어 바이트 배열 b[off]로부터 len 길이만큼 저장 |
| boolean readBoolean() | 읽은 데이터가 0이면 false 0이 아니면 true |
| byte readByte() | 1바이트를 읽어 반환 |
| char readChar() | 한 문자를 읽어 반환 |
| int readInt() | int 데이터 한개를 읽어 반환 |
| long readLong() | long 데이터 한개를 읽어 반환 |
| float readFloat() | float 데이터 한개를 읽어 반환함 |
| double readDouble() | double 데이터 한개를 읽어 반환 |
read()기본적으로 한개를 뜻하는거같다
메소드 목록에서 보듯이 파일에 저장된 다양한 데이터를 읽어올수 있다.
DataOutputStream 클래스도 생성자 한개 있습니다.
[DataOuputStream 생성자]
| 생성자 | 설명 |
|---|---|
| DataOutputStream(OutputStream out) | OutputStream 객채를 이용하여 DataOutputStream 객체를 생성 |
[DataOutputStream 메소드]
| 메소드 | 설명 |
|---|---|
| int write(byte[] b) | 바이트 배열 b를 출력함 |
| int write(byte[] b, int off, int len | 바이트 배열 b[off]로 부터 len길이 만큼 출력 |
| void writeBoolean(boolean v) | boolean 데이터를 출력함 |
| void writeByte(int v) | 1 바이트를 출력함 |
| void writeChar(int v) | 한 문자를 출력함 |
| void writeShort(int v) | short 데이터 한개를 출력함 |
| void writeInt(int v) | int 데이터 한개를 출력함 |
| void writeLong(long v) | long 데이터 한개를 출력함 |
| void writeFloat(float v) | float 데이터 한개를 출력함 |
| void writeDouble(double v) | double 데이터 한개를 출력함 |