본문 바로가기

System Programmings/Java

[Java] 파일 입출력 [ FileInputStream / FileOuputStream ]

반응형

텍스트 파일의 값을 이진수로 입출력 한다.

[FileInputStream 사용법]

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {
 public static void main(String [] argv){
  FileInputStream reader=null;
  try {
   reader = new FileInputStream("data.txt");
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  byte [] str = new byte[16];
  try {
   reader.read(str);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  finally{
   
    try {
     reader.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }
  String m = new String(str);
  System.out.println(m);
  
 }
}


-----------------------------
[FileouputStream 사용법]

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

 

public class Main {
 public static void main(String [] argv){
  FileOutputStream writer = null;
  try {
   writer = new FileOutputStream("data.txt", true) ; // 기존 파일 내용 이어서 쓰기
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  byte [] m = {'R', 'u', 'n', ' ', 'a', 'w', 'a','y'};
  try {
   writer.write(m);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  finally{
   try {
    writer.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }  
 }
}

반응형