如果你會寫到分段下載檔案 (續傳),那麼一定會需要使用分段寫入檔案 (續寫)
寫入一次後,如果意外中斷,還可以從上次的地方開始寫入
不需要再重頭開始寫入
有效節省時間

using UnityEngine;
using System.Collections;
using System.IO;

public class NewBehaviourScript : MonoBehaviour {

    public Texture2D t; // 請在這裡從外部拖一張圖片進來

    void Start () {
         byte [] b = t.EncodeToJPG ();

         MyWrite (b, 0, 30000, "A.jpg"); // 第一次寫入: 0 ~ 30000
         MyWrite (b, 30000, 10000, "A.jpg"); // 第二次寫入: 30000 ~ 40000 ( 10000 代表 30000 的 後面 10000 個
         MyWrite (b, 40000, b.Length - 40000, "A.jpg"); // 第三次寫入:( 30000 的後面全部寫入,所以總長度最後要減 30000 才是剩於大小
     }

     void MyWrite(byte [] b, int star, int end, string filePath){
         using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate)) {
             fs.Position = star;
             fs.Write (b, star, end);
             fs.Flush ();
         }
    }
}


執行結果(1):只執行第一次寫入,二、三次註解掉
MyWrite (b, 0, 30000, "A.jpg"); // 第一次寫入
// MyWrite (b, 30000, 10000, "A.jpg");  // 第二次寫入
// MyWrite (b, 40000, b.Length - 40000, "A.jpg"); // 第三次寫入


A


執行結果(2):只執行第三次寫入,一二次註解掉
//MyWrite (b, 0, 30000, "A.jpg"); // 第一次寫入
// MyWrite (b, 30000, 10000, "A.jpg");  // 第二次寫入
MyWrite (b, 40000, b.Length - 40000, "A.jpg"); // 第三次寫入

B


執行結果(3):只執行第次寫入,、三次註解掉
//MyWrite (b, 0, 30000, "A.jpg"); // 第一次寫入
MyWrite (b, 30000, 10000, "A.jpg");  // 第二次寫入
// MyWrite (b, 40000, b.Length - 40000, "A.jpg"); // 第三次寫入

C  

arrow
arrow
    全站熱搜

    黃彥霖 發表在 痞客邦 留言(0) 人氣()