2012-11-05 3 views
0

FileOutputStream과 함께 존재하는 파일을 작성하는 방법은 무엇입니까? 내가 두 번이 프로그램을 실행하면, 두 번째 oosfos 코드에서이미 존재하는 파일을 작성하십시오.

public class ReadFile { 
    static FileOutputStream fos = null; 
    static ObjectOutputStream oos = null; 
    public static void main(String[] args) throws IOException, ClassNotFoundException { 

     File f = new File("file.tmp"); 
     if (f.exists()) { 
      //How to retreive an old oos to can write on old file ? 
      oos.writeObject("12345"); 
      oos.writeObject("Today"); 
     } 
     else 
     { 
      fos = new FileOutputStream("file.tmp"); 
      oos = new ObjectOutputStream(fos); 
     } 
     oos.close(); 
    } 
} 

답변

2
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f,true)); 

에 진정한 인수를 추가

0
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f, true)); 

널 (null), 당신은 너무 oosnull입니다 ObjectOutputStream oos = null; 있습니다. 초기화해야합니다. 이처럼 : 파일을 overrite하지 않으려면이 파일에 추가하려는 경우

public class ReadFile { 
    static FileOutputStream fos = null; 
    static ObjectOutputStream oos = null; 
    public static void main(String[] args) throws IOException, ClassNotFoundException { 

     File f = new File("file.tmp"); 
     oos = new ObjectOutputStream(new FileOutputStream(f, true)); 
     if (f.exists()) { 
      //How to retreive an old oos to can write on old file ? 
      oos.writeObject("12345"); 
      oos.writeObject("Today"); 
     } 
     else 
     { 
      fos = new FileOutputStream(f, true); 
      oos = new ObjectOutputStream(fos); 
     } 
     oos.close(); 
    } 
} 
0

는 파일 또는 파일의 OutputStream 생성자

new FileOutputStream(new File("Filename.txt"), true); 

Parameters: 
name - the system-dependent file name 
append - if true, then bytes will be written to the end of the file rather than the beginning 
0

일반 텍스트를 쓰려면 FileOutputStream 대신 FileWriter을 사용해보십시오.

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true))); 
    out.println("the text"); 

두 번째 매개 변수 (true)는 파일에 추가 할 말할 것이다.

0

그냥 true

FileOutputStream d = new FileOutputStream(file, append); 
로 설정된 두 번째 인수로 새로운 FileOutputStream를 만들
관련 문제