【发布时间】:2020-05-21 19:08:26
【问题描述】:
我必须在磁盘上写入 4GB 短 [] 数组,因此我找到了一个写入数组的函数,我正在努力编写从磁盘读取数组的代码。我通常用其他语言编写代码,所以如果我的尝试到目前为止有点可悲,请原谅我:
using UnityEngine;
using System.Collections;
using System.IO;
public class RWShort : MonoBehaviour {
public static void WriteShortArray(short[] values, string path)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
foreach (short value in values)
{
bw.Write(value);
}
}
}
} //Above is fine, here is where I am confused:
public static short[] ReadShortArray(string path)
{
byte[] thisByteArray= File.ReadAllBytes(fileName);
short[] thisShortArray= new short[thisByteArray.length/2];
for (int i = 0; i < 10; i+=2)
{
thisShortArray[i]= ? convert from byte array;
}
return thisShortArray;
}
}
【问题讨论】:
-
您可能只读取所有字节和convert them to short,但 4gig 的数据很多!可能有内存问题。
-
我以前从未在 C# 中看到过这种变量声明:
thisShort : short[] = new short[]; -
嗨,对不起,我解决了这个问题。这是一些音频分析数据,需要 20-30 分钟来计算,所以如果我可以将它保存到磁盘,我可以节省时间来研究它。它是 50*44100*600 短值。
-
第二个代码不会编译,因为没有返回任何内容,也没有从读取中存储任何内容。该代码试图将输入分成两个相等的部分,但如果不是 4 的倍数,您将有一个具有奇数字节的左半部分和右半部分,并且读取最后一个短 (int16) 也将不起作用。
-
我认为与其依赖数组的长度,不如使用
while (fs.Position < fs.Length)。我也会切换到LinkedList<short>,这样我就不必分配 4GB 的连续内存。 LinkedList 保持指向下一个元素/项的指针,因此内存分配不需要是连续的。
标签: c# filestream binarywriter