[Java] IO 예제
- BACKEND/Java
- 2017. 11. 2. 16:15
바이트 스트림 예제
package bytestream; import java.io.IOException; public class ByteTest1 { public static void main(String[] args) { byte data[] = new byte[10];
System.out.print("10개의 문자 입력 : ");
try { System.in.read(data); } catch (IOException e) { e.printStackTrace(); }
System.out.println("입력된 값 : "); /* for(int i =0; i<data.length;i++) { System.out.print((char)data[i]); } */
//향상된 for문 for(byte b :data) { System.out.print((char)b); } } } |
package bytestream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class ByteTest2 { static void StreamTest(InputStream in, OutputStream out) throws IOException{ int input = System.in.read();
while(input != -1) { out.write((char)input); input = System.in.read(); } } public static void main(String[] args)throws IOException { StreamTest(System.in,System.out);
/* int input = 0; while(true) { input = System.in.read();
if(input == -1) { break; } System.out.print((char)input); } */
/* int input = 0; while((input = System.in.read())!= -1) { System.out.print((char)input); } */ } } |
package bytestream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; public class FileTest1 { public static void main(String[] args) throws IOException{ //파일로 부터 입력받아 콘솔로 출력하는 예제 FileInputStream fin = new FileInputStream("c:\\lsh\\test.txt");
int input = 0; while(input != -1) { input = fin.read();
//System.out.print((char)input); OutputStream out = System.out; out.write((char)input); out.flush(); }
fin.close(); } } |
package bytestream; import java.io.FileOutputStream; import java.io.IOException; public class FileTest2 { public static void main(String[]args) throws IOException { // 키보드로부터 입력받아 파일로 출력 // inputstream은 파일이 없으면 에러가 나며 저장되지 않지만 outputstream은 파일을 만들어준다. FileOutputStream fout = new FileOutputStream("c:\\lsh\\test2.txt", true); //두번째 인자 값에 true로 줬을때 값을 덮어 쓰지 않고 값을 추가해준다. int input = 0; while(true) { input = System.in.read(); if(input == -1) break; fout.write((char)input); fout.flush(); } fout.close(); } } /* * java jcopy a.txt b.txt -> 파일 복사 */ |
package bytestream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class FileTest3 { public static void main(String[] args) throws IOException{ FileOutputStream fout = new FileOutputStream("c:\\lsh\\test3.txt");
for(int i=1;i<10; i++) { String data = i + "번째 줄입니다.\n"; System.out.println(data); fout.write(data.getBytes()); }
fout.close(); } } |
package bytestream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataTest { public static void main(String[] args) throws IOException { // DataInputStream, DataOutputStream FileOutputStream fout = new FileOutputStream("c:\\lsh\\test4.txt");
DataOutputStream dout = new DataOutputStream(fout);
dout.writeChar('가'); //문자열 저장 dout.writeInt(10); //숫자 저장 dout.writeDouble(3.14); //소수점 저장 dout.writeBoolean(true); //true, false 저장
dout.close(); fout.close();
DataInputStream din = new DataInputStream (new FileInputStream("c:\\lsh\\test4.txt"));
System.out.println(din.readChar()); System.out.println(din.readInt()); System.out.println(din.readDouble()); System.out.println(din.readBoolean()); din.close(); } } |
package bytestream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class RandomAccessFileTest { public static void main(String[] args) throws IOException { int data[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; RandomAccessFile raf = new RandomAccessFile("c:\\lsh\\text5.txt","rw"); for(int i=0; i<data.length;i++) { raf.writeInt(data[i]); } raf.seek(0); System.out.println(raf.readInt()); raf.seek(8); System.out.println(raf.readInt()); raf.seek(4*3); // 4byte * 3 => 40 , int = 4byte System.out.println(raf.readInt()); } } |
오브젝트 스트림
package bytestream; import java.io.Serializable; public class Employee implements Serializable { //내부적 데이터 직렬화 private int no; private String name; private String job; private int dept; private double point;
public Employee() {} public Employee(int no, String name, String job, int dept, double point) { super(); this.no = no; this.name = name; this.job = job; this.dept = dept; this.point = point; }
@Override // Annotation문법 public String toString() { return no + "\t" + name + "\t" + job + "\t" + dept + "\t" + point; }
} |
package bytestream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class ObjectTest { public static void main(String[] args)throws IOException, ClassNotFoundException { // ObjectInputStream Employee[] emp = new Employee[3]; emp[0] = new Employee(1, "홍길동", "영업",110, 1.4); emp[1] = new Employee(2, "임꺽정", "기술",111, 1.5); emp[2] = new Employee(3, "신돌석", "개발",112, 1.7);
//System.out.println(emp[0]);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:\\lsh\\test6.txt")); oos.writeObject(emp[0]); oos.writeObject(emp[1]); oos.writeObject(emp[2]);
oos.close();
System.out.println("**************사원*************"); System.out.println("사번\t이름\t업무\t부서번호\t인사점수"); System.out.println("------------------------------");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c:\\lsh\\text7.txt"));
for(int i=0; i<3; i++) { Employee e = (Employee)ois.readObject(); System.out.println(e); } ois.close(); } } |
문자열 스트림
package charstream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class CharTest1 { static void StreamTest(InputStream in) throws IOException{ InputStreamReader isr = new InputStreamReader(in); //bytestream을 문자 스트림으로 변환 BufferedReader br = new BufferedReader(isr);
/* int input = in.read();
while(input != -1) { System.out.print((char)input); input = isr.read(); } */
String input = br.readLine(); while(input != null) { System.out.println(input); input = br.readLine(); } isr.close(); br.close(); } public static void main(String[] args)throws IOException { StreamTest(System.in); } } |
package charstream; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class FileTest1 { public static void main(String[] args) throws IOException{ //파일로 부터 입력받아 콘솔로 출력하는 예제 BufferedReader br = null; try { br = new BufferedReader(new FileReader("c:\\lsh\\test.txt"));
String input = br.readLine(); while((input=br.readLine()) != null) { System.out.println(input); }
} catch(FileNotFoundException err) { System.out.println("파일을 찾을 수 없다. :" + err); } catch(IOException err) { err.printStackTrace(); } finally { try { br.close(); }catch(Exception err) {} } } } |
package charstream; import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class FileTest2 { public static void main(String[]args) throws IOException { // 키보드로부터 입력받아 파일로 출력 bytestream -> charstream 으로 바꾸기 FileWriter fout = new FileWriter("c:\\lsh\\test2.txt", true); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr);// 속도를 빠르게 해주는 bufferedreader
String input = null; while(true) { input = br.readLine();
if(input == null) break;
fout.write(input); fout.flush(); } fout.close(); isr.close(); br.close(); } } /* * java jcopy a.txt b.txt -> 파일 복사 */ |
package charstream; import java.io.IOException; import java.io.PrintWriter; public class FileTest3 { public static void main(String[] args) throws IOException{ //FileWriter fout = new FileWriter("c:\\lsh\\test3.txt"); PrintWriter pw = new PrintWriter("c:\\lsh\\test3.txt");
for(int i=1;i<10; i++) { String data = i + "번째 줄입니다.\n"; System.out.println(data); //fout.write(data); pw.print(data); } //fout.close(); pw.close(); } } |
package charstream; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class FileTest4 { public static void main(String[] args) throws IOException{ //버퍼로 포장해서 성능을 개선하기 위해 //PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("c:\\lsh\\sungjuk.txt"))); //위의 코드와 밑의 코드는 같은 동작을 한다. PrintWriter pw = new PrintWriter("c:\\\\lsh\\\\sungjuk.txt");
pw.println("*****************************성적표***********************"); pw.println("--------------------------------------------------------"); pw.printf("%3s : %5d %5d %5.1f %n","홍길동", 98, 67,(float)((98+67)/2)); // %3s = 3자리 String %5d = 5자리 decimal %5.1f = 5자리 float
pw.printf("%3s : %5d %5d %5.1f %n","임꺽정", 98, 67,(float)((98+67)/2)); pw.printf("%3s : %5d %5d %5.1f %n","신돌석", 98, 67,(float)((98+67)/2)); pw.printf("%3s : %5d %5d %5.1f %n","유비", 98, 67,(float)((98+67)/2)); pw.close();
//파일에 저장된 내용을 읽어서 콘솔로 출력 } } |
파일 테스트 예제
package charstream; import java.io.File; import java.util.Date; public class FileTest { public static void main(String[] args) { File f = new File("c:\\lsh\\test3.txt");
if(f.exists()) { System.out.println("파일의 이름 : "+ f.getName()); System.out.println("상대 경로 : "+ f.getPath()); System.out.println("절대 경로 : "+ f.getAbsolutePath()); System.out.println("크기 : "+ f.length()+ "byte"); System.out.println("마지막 수정일자 : "+ new Date(f.lastModified())); }else { System.out.println("파일이 존재하지 않는다."); }
f.delete(); //파일 삭제 } } |
'BACKEND > Java' 카테고리의 다른 글
[Java] Window Programming - <Layout> (0) | 2017.11.06 |
---|---|
[Java] Window Programming (0) | 2017.11.06 |
[Java] Thread 예제 (0) | 2017.11.02 |
[Java] Thread (0) | 2017.11.01 |
[Java] IO (0) | 2017.10.30 |