** I/O (입출력) : java.io
입력장치 App(Java) 출력장치

Stream
-ByteStream (=NodeStream) : 모든 data를 1byte / ~Stream
-CharacterStream (=FilterStream) : 2byte / I:~Reader
O:~Writer
StdInOutTest
package com.kitri.io;
import java.io.IOException;
public class StdInOutTest {
public static void main(String[] args) {
// System class의 static field인 out의 Type인 PrintStream의 prinln method를 쓴 것
// System.out.println();
// int x = System.in.read();
// 에러 : IOException가보니 nonRuntimeException임.
try {
// System.out.print("입력 : ");
// int x = System.in.read();
// System.out.println("1. x == " + x);
// 첫번째 숫자의 아스키 코드 값 받아옴
// System.out.println("1. x == " + (char)x);
System.out.println("입력2 : ");
byte b[] = new byte[100];
int x = System.in.read(b);
System.out.println("2. x == " + x);
// 입력한 문자들의 총 byte와 엔터\n +2 byte
int len = b.length;
for (int i = 0; i < len; i++) {
System.out.println(b[i]);
// 입력한 문자들의 아스키코드값
}
String s= new String(b,0,x-2);
// byte배열을 String값으로 변환(100짜리를 문자길이만큼으로
System.out.println("s == "+s);
// 입력한 문자 출력됨 >> 100byte 넘는 문자는 안됨
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileTest
package com.kitri.io;
import java.io.*;
public class FileTest {
public static void main(String[] args) {
InputStream in =null;
OutputStream out =null;
try {
File infile = new File("e:\\iotest\\hello.txt");
in = new FileInputStream(infile);
long length = infile.length();
// file클래스의 method length(): 파일의 길이
byte b[] = new byte[(int)length];
int x = in.read(b);
String str = new String(b,0,x);
// byte b[]를 string화 시킴
System.out.println(x+"bytes read !!!");
System.out.println(str);
File outfile = new File("e:\\iotest\\hello_copy.txt");
out = new FileOutputStream(outfile);
out.write(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// 상위 Exception은 먼저 나올 수 없다.(Eclipse가 알아서 해줌)
e.printStackTrace();
} finally {
try {
if(in!=null)
in.close();
if(out!=null)
out.close();
// io는 무조건 열었으면 닫아야한다.
} catch (IOException e) {
e.printStackTrace();
}
}
}
[출처] 빡쏘끼룩
'IT > JAVA' 카테고리의 다른 글
[Java] I/O 3(입출력) (java.io) - NotePad 만들기 (0) | 2020.11.13 |
---|---|
[Java] I/O 2(입출력) (java.io) - reader Class(reader, fileReader, bufferedReader) (0) | 2020.11.11 |
[Java] Exception - Runtime Exception (ArithMeticException, IndexOutOfBoundsE, NumberFormatException) (0) | 2020.10.23 |
[Java] JCF(Java Collection Framework) - Collection / Map (0) | 2020.10.16 |
[Java] Swing - CardLayout (창 넘어가기) (0) | 2020.10.14 |