簡體   English   中英

FileInputStream 和 FileOutputStream:讀寫同一個文件

[英]FileInputStream and FileOutputStream: Read and write to the same file

我創建了一個內容為“Hello”的文本文件,我試圖從文件中讀取這些字符並將其再次寫回同一個文件。

假設: 1. 文件現在有內容“Hello”(覆蓋) 2. 文件現在有內容“HelloHello”(附加) 3. 文件現在有內容無限“Hello”(或拋出異常)

實際結果:原來的“Hello”字符從文本文件中刪除,文件為空。

實測

    @Test
    public void testCopyStream() throws IOException {
        File workingDir = new File(System.getProperty("user.dir"));
        File testFile = new File(workingDir, "/test.txt");

        FileReader fin = new FileReader(testFile);
        FileWriter fos = new FileWriter(testFile);
        copyStream(fin, fos);
        fin.close();
        fos.close();
}

我創建了以下方法來將InputStream中的數據“復制”到OutputStream中:

private void copyStream(Reader in, Writer out) throws IOException {
        int b;
        while ((b = in.read()) != -1) {
           out.write(b);
        }
    }

我嘗試使用調試器找出問題所在,調試器顯示b = in.read()在 while 循環的第一次迭代中被分配了-1 然后我在檢查文件內容的同時逐步執行代碼,發現“Hello”關鍵字在語句final FileWriter fos = new FileWriter(testFile);之后立即從文件中刪除。 被執行。

我首先認為這是由於InputStreamOutputStream指向同一個文件,所以為了執行安全,文件被 JVM 有點“鎖定”?

所以我嘗試交換這兩行:

        FileWriter fos = new FileWriter(testFile);
        FileReader fin = new FileReader(testFile);
        

結果是一樣的:文件內容在語句FileWriter fos = new FileWriter(testFile);之后被刪除了。

我的問題是:為什么內容會被FileWriter清除?。 這是與 FileDescriptor 相關的一些行為嗎? 有沒有辦法讀取和寫入同一個文件?

僅供參考,

  1. copyStream()方法工作正常,我已經用其他測試對其進行了測試。
  2. 這不是關於使用append()方法而不是write()

聲明FileWriter fos = new FileWriter(testFile); 截斷現有文件。

使用流式訪問來讀寫同一個文件沒有意義,因為這不會提供可靠的結果。 如果要讀取/寫入同一文件,請使用 RandomAccessFile:這會調用查找當前 position 並在文件的不同位置執行讀取或寫入。

https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html

FileWriter實際上會在寫入之前刪除文件中的所有內容。 要保留文本,請使用

new FileWriter(file, true);

真正的參數是filewriter的append參數。 否則它只會覆蓋一切

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM