第一个blog, 些什么呢? 就写了一个最简单的小例子,呵呵
总体来讲, 感觉还不错, 对各种情况有一定的措施, 比一般的例子要负责任一些
public static string m_FileName { set; get; } // 读/写的文件名(包含绝对路径)
private static bool m_ReadReady; //是否读取成功
private static bool m_WriteReady; //是否保存成功
// 读ASCII文件中的数据到 double[][]
public static double[][] readASCII2Mat()
{
return readASCII2Mat(',');
}
public static double[][] readASCII2Mat(char separator)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
m_FileName = ofd.FileName;
return readASCII2Mat(m_FileName, separator);
}
public static double[][] readASCII2Mat(String fileName, char separator)
{
double[][] data = null;
FileInfo tFi = new FileInfo(fileName);
if (tFi.Exists == false)
{
m_ReadReady = false;
return null;
}
StreamReader sReader = new StreamReader(fileName);
int rowCount = 0;
int colCount = 0;
int maxLength = 1024;
double[][] temp = new double[maxLength][];
while (!sReader.EndOfStream)
{
if (rowCount > maxLength) //如果总行数超过了maxLength,需要扩容
{
double[][] temp2 = new double[maxLength][];
for (int i = 0; i < maxLength; i++)
temp2[i] = temp[i];
if (maxLength <= Math.Pow(2, 16)) //maxLenth 小于 2^16即 64K时,可以倍增行数
maxLength *= 2;
else
maxLength += (int)Math.Pow(2, 16);
temp = new double[maxLength][];
for (int i = 0; i < temp2.Length; i++)
temp[i] = temp2[i];
}
string str = sReader.ReadLine(); // 读行
string[] strList = str.Split(separator);// 将一段string使用分隔符进行分割
colCount = colCount < strList.Length ? strList.Length : colCount;
double[] newRow = new double[strList.Length];
for (int j = 0; j < strList.Length; j++)
{
newRow[j] = Convert.ToDouble(strList[j]); // str2num 的使用方法
}
temp[rowCount] = newRow;
rowCount++;
}
data = new double[rowCount][];
for (int i = 0; i < rowCount; i++)
{
data[i] = new double[temp[i].Length];
for (int j = 0; j < temp[i].Length; j++)
data[i][j] = temp[i][j];
}
m_ReadReady = true;
return data;
}
public static void readMessageBox()
{
if (m_ReadReady)
MessageBox.Show(m_FileName, "读取成功");
else
MessageBox.Show("读取失败", "读取失败");
}
//将2D数组保存为ASCII文件
public static bool writeMat2ASCII(double[][] data)
{
return writeMat2ASCII(data, ',');
}
public static bool writeMat2ASCII(double[][] data, Char seperator)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.ShowDialog();
m_FileName = sfd.FileName;
return writeMat2ASCII(data, m_FileName, seperator);
}
public static bool writeMat2ASCII(double[][] data, String fileName, Char separator)
{
if (fileName == null || fileName == "")
{
m_WriteReady = false;
return false;
}
// FileInfo tFi = new FileInfo(fileName);
StreamWriter strW = new StreamWriter(fileName);
for (int i = 0; i < data.Length; i++)
{
for (int j = 0; j < data[i].Length - 1; j++)
{
strW.Write(Convert.ToString(data[i][j]));
strW.Write(separator);
}
strW.Write(Convert.ToString(data[i][data[i].Length - 1]));
if (i < data.Length - 1)
strW.Write("/r/n");
}
m_WriteReady = true;
strW.Close();
return true;
}
public static void writeMessageBox()
{
if (m_WriteReady)
MessageBox.Show(m_FileName, "保存成功");
else
MessageBox.Show("保存失败", "保存失败");
}