본문 바로가기

콩's EDUCATION/콩's JAVA_RUN

FileInputStream / FileOutputStream / FileReader / FileWriter

FileInputStream / FileOutputStream /

FileReader / FileWriter 출력


cf.객체 생성만 이름 변경해주면 똑같다.

 

import java.io.*;
// FileCopyTest.java ==> copy.txt
// a.txt b.txt ==> a.txt 입력 파일 없다. 오류 발생.
// src/FileCopyTest.java copy.txt => copy.txt
// src/JoinTest.java copy.txt => 기존 내용은 삭제된다.
// true로 소스 변경한 후에
// src/FileCopyTest.java copy.txt => 기존 내용 유지 출력.

public class FileCopyTest {
 public static void main(String[] args) throws IOException {
  FileInputStream fi = null;
  FileOutputStream fo = null;

  try {
   fi = new FileInputStream(args[0]);
   /**
    * args[0] 파일 존재 x : Exception 발생

args[0] 파일 존재 o : 정상 입력 수행 프로젝트 폴더
    * 기준 폴더 : src/....폴더
    */
   fo = new FileOutputStream(args[1], true);
   /**
    * args[1] 파일 존재 x : args[1] 이름 empty 파일 생성 args[1] 파일 존재 o : 원래 저장
    * 내용을 삭제 후 출력 할 것인가 혹은 유지 후 출력 하느냐. 매개변수 내에 false(default)가 있으면 삭제
    * 후 출력 true면 내용 유지 후 출력한다. 프로젝트 폴더 기준 폴더 : src/...폴더
    */

   // 입력문자 저장 변수
   int result = 0;
   while (result != -1) {
    result = fi.read();
    fo.write(result);
   }
  } catch (FileNotFoundException e) {
   System.out.println("파일 이름 오류");
  } catch (IOException e) {
   System.out.println("입출력 오류");
  } // 반드시 실행 의무 문장들 : finally
  finally {
   try {
    fi.close();
    // 파일 입력 완료 (args[0])
    fo.close();
    // 파일 출력 완료 (args[1] 파일 대기중인 다른 프로그램에서 문제 발생가능 (없으면)
   } catch (IOException e) {
   }
  }
 }
}

 

 

 

FileCopyTest.java