2011-02-01 8 views
-1

텍스트 필드에 항목이있을 때마다 파일에 쓰기위한 코드가 있습니다. 그러나 프로세스가 끝나면 항목이 다시 만들어지면 파일에 대한 항목을 계속 쓰는 대신 파일이 다시 쓰여 지므로 이전 데이터가 손실됩니다. 기존 응용 프로그램을 다시 작성하면 나중에 응용 프로그램을 닫은 후에도 해당 데이터를 읽을 수 있습니다.파일 읽기 및 쓰기

쓰기 프로세스의 코드가 주어진다 :

public boolean writeToFile(String dataLine) { 
    dataLine = "\n" + dataLine; 


try { 
    File outFile = new File(filepath); 

    dos = new DataOutputStream(new FileOutputStream(outFile)); 

    dos.writeBytes(dataLine); 
    dos.close(); 
} catch (FileNotFoundException ex) { 
    return (false); 
} catch (IOException ex) { 
    return (false); 
} 
return (true); 

}

하는 사람이 pls는 필요에 따라 코드를 변경하고 나에게 그것을 게시 할 수 없습니다.

답변

1

사용 APPEND와 생성자 FileOutputStream(File file, boolean append) = 사실

1

append 모드로 파일을 엽니 다.

만들 그것을

dos = new DataOutputStream(new FileOutputStream(outFile),true); 
2

에서 [FileOutputStream에 대한 자바 API] [1] 상태 :

public FileOutputStream(String name, 
         boolean append) 
       throws FileNotFoundException) 

지정된 파일에 기입하는 파일 출력 스트림을 작성 이름. 2 번째의 인수가 true의 경우, 바이트는 파일의 선두가 아니고 파일의 말미에 기입 해집니다. 이 파일 연결을 나타 내기 위해 새 FileDescriptor 객체가 만들어집니다.

그래서, 당신의 코드는 다음과 같아야합니다

public boolean writeToFile(String dataLine) { 
    dataLine = "\n" + dataLine; 
    try { 
    File outFile = new File(filepath); 
    dos = new DataOutputStream(new FileOutputStream(outFile,true)); 
    dos.writeBytes(dataLine); 
    dos.close(); 
    } catch (FileNotFoundException ex) { 
    return (false); 
    } catch (IOException ex) { 
    return (false); 
    } 
    return (true); 
} 

[1] : http://download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.lang.String, 부울)