Java/입출력
입출력 파일 생성및 파일 읽기
Bohemian life
2012. 4. 13. 22:53
package com.output; // 입출력으로 파일생성 및 파일 읽기 import java.io.IOException; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class FileOuputstreamEx { public static void main(String[] args) { FileOutputStream fos = null; FileInputStream fin = null; try{ //파일 생성 fos = new FileOutputStream("c:\\fileout.txt"); //fos = new FileOutputStream("c:\\fileout.txt",true); //기존 파일이 있으면 이어쓰기함 String message = "Hello File!! 즐거운 하루!!"; //String -> byte[] //생성된 파일에 데이터 입력 fos.write(message.getBytes()); //존재하는 파일을 읽어드림 fin = new FileInputStream("c:\\fileout.txt"); byte[]b = new byte[fin.available()]; //파일로부터 데이를 읽어드림 fin.read(b); //byte ->String //문자열 출력 System.out.println(new String(b)); }catch(FileNotFoundException fnfe){ fnfe.printStackTrace(); }catch(IOException ie){ ie.printStackTrace(); }finally{ try{ //스트림을 닫음 if(fos != null) fos.close(); if(fin != null) fin.close(); }catch(IOException ioe){ ioe.printStackTrace(); } } } }