快速入門:讀取和寫入檔案 (HTML)

[ 本文的目標對象是撰寫 Windows 執行階段 App 的 Windows 8.x 和 Windows Phone 8.x 開發人員。如果您正在開發適用於 Windows 10 的 App,請參閱 最新文件 ]

使用 StorageFile 物件讀取和寫入檔案。

先決條件

範例中使用的檔案

這些範例的所有程式碼都是取自檔案存取範例,而且取決於該範例的全域 sampleFile 變數。這個變數代表在這些範例中,這個範例寫入和讀取的檔案 (sample.dat)。

檔案存取範例會建立 sample.dat 檔案,並儲存傳回的 storageFile 物件,像這樣:

Windows.Storage.ApplicationData.current.localFolder.createFileAsync("sample.dat",
    Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) {
        sampleFile = file;
    });

注意  您必須先在應用程式資訊清單中宣告必要的功能,才能在媒體櫃中建立檔案。若要深入了解檔案存取和功能,請參閱檔案存取和權限使用 Windows 執行階段來存取使用者資源

 

寫入檔案

如果您有一個可寫入的檔案以及一個代表這個檔案的 storageFile,這些步驟告訴您如何寫入檔案。

將文字寫入檔案

呼叫 fileIO 類別的 writeTextAsync 方法,將文字寫入您的檔案。

檔案存取範例會顯示如何呼叫 writeTextAsync(file, contents) 來將任意文字寫入它的 sampleFile,像這樣:

Windows.Storage.FileIO.writeTextAsync(sampleFile, "Swift as a shadow").then(function () {
    // Add code to do something after the text is written to the file
});

雖然 writeTextAsync 方法沒有傳回值,但是您仍然可以使用 thendone 來宣告函式,並在文字寫入到檔案後執行其他工作,如範例所示。

使用緩衝區將位元組寫入檔案

  1. 取得您想寫入檔案的位元組緩衝區。

    例如,檔案存取範例會呼叫 convertStringToBinary,根據任意字串取得位元組緩衝區,像這樣:

    var buffer = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(
        'What fools these mortals be', Windows.Security.Cryptography.BinaryStringEncoding['']
    );
    
  2. 呼叫 fileIO 類別的 writeBufferAsync 方法,將緩衝區的位元組寫入您的檔案。

    檔案存取範例會顯示如何使用 writeBufferAsync,將位元組從緩衝區寫入它的 sampleFile,像這樣:

    Windows.Storage.FileIO.writeBufferAsync(sampleFile, buffer).then(function () {
        // Add code to do something after the text is written to the file
    });
    

    雖然 writeBufferAsync 沒有傳回值,但是您仍然可以使用 thendone 來宣告函式,並在檔案寫入文字後執行其他工作,如範例所示。

使用交易的資料流將文字寫入檔案

  1. 呼叫 storageFile.openTransactedWriteAsync 方法,開啟傳入您檔案的資料流。當開啟作業完成時,會傳回檔案內容的資料流。

    檔案存取範例會顯示如何藉由呼叫 storageFile.openTransactedWriteAsync 方法開啟檔案 (sampleFile) 上的資料流,像這樣:

    sampleFile.openTransactedWriteAsync().then(writeToStream);
    

    確定宣告一個函式 (例如 writeToStream) 來擷取 transaction (類型 StorageStreamTransaction),以便讓您能夠在方法完成後寫入檔案,像這樣:

    function writeToStream(transaction) {
        // Add code to use the stream to write to your file
    }
    
  2. 按照這些步驟將程式碼加入您的 writeToStream 函式,在 storageFile.openAsync 方法完成後將文字寫入您的檔案。

    1. 建立新的 dataWriter 物件並呼叫 dataWriter.writeString 方法,以使用 transaction 將文字寫入資料流。

      檔案存取範例示範如何將文字寫入資料流,像這樣:

      var dataWriter = new Windows.Storage.Streams.DataWriter(transaction.stream);
      dataWriter.writeString("Swift as a shadow");
      
    2. 呼叫 dataWriter.storeAsynctransaction.commitAsync 方法,以將文字儲存至檔案並關閉資料流。

      檔案存取範例會顯示如何將文字儲存至檔案並關閉資料流,像這樣:

      dataWriter.storeAsync().then(function () {
          transaction.commitAsync().done(function () {
              // Text in stream has been saved to the file
              transaction.close();
          });
      });
      

您可以下載檔案存取範例,查看函式的內容中這些程式碼範例。

從檔案讀取

這些步驟顯示如果您有可讀取的檔案以及代表這個檔案的 storageFile,如何從檔案讀取它們。

從檔案讀取文字

呼叫 fileIO 類別的 readTextAsync 方法,即可從檔案讀取文字。

檔案存取範例會顯示如何呼叫 readTextAsync(file) 讀取它的 sampleFile,進而從檔案讀取文字,像這樣:

Windows.Storage.FileIO.readTextAsync(sampleFile).then(function (contents) {
    // Add code to process the text read from the file
});

您可以使用 thendone 來宣告函式,抓取和處理從檔案讀取的文字。readTextAsync 方法完成後,會將文字傳遞到這個函式做為 String 物件 (範例中的 contents)。

使用緩衝區從檔案讀取位元組

呼叫 fileIO 類別的 readBufferAsync 方法,將您檔案中的位元組讀到緩衝區。

檔案存取範例會顯示如何藉由呼叫 readBufferAsync,從檔案讀取位元組到緩衝區,像這樣:

Windows.Storage.FileIO.readBufferAsync(sampleFile).then(function (buffer) {
    // Add code to process the text read from the file
});

您可以使用 thendone 來宣告函式,在 readBufferAsync 方法完成後,抓取和處理 buffer (類型 IBuffer) 資料。

例如,檔案存取範例會抓取 buffer 並使用 dataReader 物件來讀取 buffer 的長度,像這樣:

Windows.Storage.FileIO.readBufferAsync(sampleFile).then(function (buffer) {
    var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
    var output = dataReader.readString(buffer.length);
});

當然,以這種方式讀取 buffer 的長度不是特別有用,但是您可以更有創意的方式來決定處理 buffer 的方式。您可以看看 dataReader 類別中提供的方法,以取得一些想法。

使用資料流從檔案讀取文字

  1. 呼叫 storageFile.openAsync 方法,開啟檔案的資料流。當開啟作業完成時,會傳回檔案內容的資料流。

    檔案存取範例會顯示如何藉由呼叫 storageFile.openAsync 方法開啟檔案 (sampleFile) 上的資料流,像這樣:

    sampleFile.openAsync(Windows.Storage.FileAccessMode.readWrite).then(readFromStream);
    

    確定您宣告函式 (如 readFromStream) 來抓取資料流 (類型 IRandomAccessStream),如此一來,就可以在方法完成後從檔案讀取,像這樣:

    function readFromStream(readStream) {
        // Add code to use the stream to read text from your file
    }
    
  2. 按照這些步驟將程式碼加入您的 readFromStream 函式,在 storageFile.openAsync 方法完成後從您的檔案讀取文字。

    1. 取得 dataReader 物件以便從 readStream 讀取。

      檔案存取範例會顯示如何取得 dataReader,像這樣:

      var dataReader = new Windows.Storage.Streams.DataReader(readStream);
      
    2. 呼叫 dataReader.loadAsyncdataReader.readString 方法來讀取文字。

      檔案存取範例示範如何讀取文字,像這樣:

      
      dataReader.loadAsync(readStream.size).done(function (numBytesLoaded) {
          var fileContent = dataReader.readString(numBytesLoaded);
          // Process text read from the file
          dataReader.close();
      });
      

您可以下載檔案存取範例,查看函式的內容中這些程式碼範例。

摘要與後續步驟

現在,如果您有一個代表檔案的 storageFile,應該了解如何從檔案讀取和寫入。

若要深入了解使用影像檔案,請參閱如何選取和顯示影像如何解碼影像以及使用 Blob 儲存和載入內容範例

相關主題

從檔案存取資料

快速入門:使用檔案選擇器存取檔案

如何選取和顯示影像

如何解碼影像

檔案存取和權限

檔案存取範例

使用 Blob 儲存和載入內容範例

參考

Windows.Storage.StorageFile class

Windows.Storage.Streams.DataReader class

Windows.Storage.Streams.DataWriter class