當我搜索方法有關通過使用SharpZipLib
文件解壓縮,我發現很多這樣的方法:在FileStream中寫入有什麼不同?
public static void TarWriteCharacters(string tarfile, string targetDir)
{
using (TarInputStream s = new TarInputStream(File.OpenRead(tarfile)))
{
//some codes here
using (FileStream fileWrite = File.Create(targetDir + directoryName + fileName))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
fileWrite.Write(data, 0, size);
}
else
{
break;
}
}
fileWrite.Close();
}
}
}
格式FileStream.Write
是:
FileStream.Write(byte []數組, int offset,int count)
現在我嘗試分開讀寫的一部分,因爲我想用線程來加快寫入函數中的解壓縮速度,並且我使用動態數組byte[]
和int[]
存放文件的數據和大小像下面
閱讀:
public static void TarWriteCharacters(string tarfile, string targetDir)
{
using (TarInputStream s = new TarInputStream(File.OpenRead(tarfile)))
{
//some codes here
using (FileStream fileWrite= File.Create(targetDir + directoryName + fileName))
{
int size = 2048;
List<int> SizeList = new List<int>();
List<byte[]> mydatalist = new List<byte[]>();
while (true)
{
byte[] data = new byte[2048];
size = s.Read(data, 0, data.Length);
if (size > 0)
{
mydatalist.Add(data);
SizeList.Add(size);
}
else
{
break;
}
}
test = new Thread(() =>
FileWriteFun(pathToTar, args, SizeList, mydatalist)
);
test.Start();
streamWriter.Close();
}
}
}
寫:
public static void FileWriteFun(string pathToTar , string[] args, List<int> SizeList, List<byte[]> mydataList)
{
//some codes here
using (FileStream fileWrite= File.Create(targetDir + directoryName + fileName))
{
for (int i = 0; i < mydataList.Count; i++)
{
fileWrite.Write(mydataList[i], 0, SizeList[i]);
}
fileWrite.Close();
}
}
編輯
(1)
byte[] data = new byte[2048]
到while循環將數據分配給新陣列。(2)改變
int[] SizeList = new int[2048]
到List<int> SizeList = new List<int>()
因爲INT範圍
首先,當它是一個Stream而不是StreamWriter時,調用一個變量'streamWriter'是相當混亂的。我強烈建議你把它叫做'stream'。但我非常期望問題是,當你試圖在另一個線程中寫入它時,你正在關閉「主」線程中的流。 –
哦,的確如此,我會根據你的推薦進行編輯,謝謝。 – Peter
使用類似IO的線程可能會減慢速度並使其變得越來越麻煩。使用一個線程進行IO。 – Enigmativity