请教关于一个读写文件的问题.
现在定义了一个数组:
myClass[] myArray=new myClass[10];
其中myClass是自己写的一个类.
现在想把赋好数据的myArray保存到文件中,但是FileWriter/Reader和StreamWriter/Reader好像都是针对字符(串)或字节操作的,怎么才能把myArray保存进文件,而以后又能从文件中直接读取呢?
问题点数:20、回复次数:8Top
1 楼zengkang(zengkang)回复于 2006-06-01 14:43:04 得分 5
可以把类先序列化为byte[],然后把byte[] 写入文本中!Top
2 楼bhwhy(苏秦)回复于 2006-06-01 14:44:08 得分 15
你可以把写入一个csv文件.循环一行一行向里写
Dim fs As FileStream
Dim sw As StreamWriter
fs = New FileStream(路径及名称, FileMode.Create,
strAll = strAll.Substring(1, strAll.Length - 1)
sw = New StreamWriter(fs, System.Text.Encoding.GetEncoding("gb2312"))
sw.WriteLine(stAall)
sw.Close()Top
3 楼bhwhy(苏秦)回复于 2006-06-01 14:45:32 得分 0
这是读csv文件,返回dataset
Public Function GetCSV(ByVal _CSVPath As String) As DataSet
Dim CSVDataSet As DataSet
CSVDataSet = New DataSet
Dim intClnCount As Integer 'the length of string()
Dim CSVDataTable As System.Data.DataTable
CSVDataTable = New System.Data.DataTable("myDataTable")
Dim mydc As DataColumn 'column object
Dim mydr As DataRow 'row object
Dim CSVPath As String
CSVPath = _CSVPath 'csv file's path
Dim strLine As String
strLine = ""
Dim strAryLine() As String 'a string(),read csv file's records into it
Dim mysr As System.IO.StreamReader
mysr = New System.IO.StreamReader(CSVPath)
Dim j = 0
mysr.BaseStream.Seek(0, SeekOrigin.Begin)
While (mysr.Peek > 0)
Try
strLine = mysr.ReadLine()
Dim mySplit As Char
mySplit = ","
strAryLine = strLine.Split(mySplit)
Console.WriteLine(strAryLine)
'get the length
intClnCount = strAryLine.Length
Dim i As Integer
'add the column, base on the j's value
If j < intClnCount Then
For i = 0 To intClnCount - 1
mydc = New DataColumn
CSVDataTable.Columns.Add(mydc)
j = j + 1
Next
End If
'create a new row,and get the every column's value
mydr = CSVDataTable.NewRow()
For i = 0 To intClnCount - 1
mydr(i) = strAryLine(i)
Next
'add the row into the table
CSVDataTable.Rows.Add(mydr)
j = j + 1
Catch ex As Exception
MsgBox(ex.Message())
End Try
End While
'add the table into the returned dataset
CSVDataSet.Tables.Add(CSVDataTable)
Return CSVDataSet
End FunctionTop
4 楼Harryfin(Harry)回复于 2006-06-01 16:11:40 得分 0
to zengkang:
我以前不是学c#的,请问那个函数叫什么呢? 还有就是,怎么把读出来的byte[]还原成原来的数据结构呢? 直接赋值?
to bhwhy:
感谢贴了这么多代码,不过觉得好像有点复杂. 请问有简单一点的方法吗?Top
5 楼bhwhy(苏秦)回复于 2006-06-01 16:15:06 得分 0
看着是挺多的,不复杂.Top
6 楼Harryfin(Harry)回复于 2006-06-01 19:26:18 得分 0
Dim fs As FileStream
Dim sw As StreamWriter
fs = New FileStream(路径及名称, FileMode.Create,
strAll = strAll.Substring(1, strAll.Length - 1)
sw = New StreamWriter(fs, System.Text.Encoding.GetEncoding("gb2312"))
sw.WriteLine(stAall)
sw.Close()
有个疑问,我要保存的是一个以对象为元素的数组,哪能调用substring方法呢? 这段代码好像不对?Top
7 楼bhwhy(苏秦)回复于 2006-06-01 19:33:26 得分 0
strAll = strAll.Substring(1, strAll.Length - 1)
这是我取字符串的第一到倒数第二的值。你根据需要变换一下Top
8 楼Harryfin(Harry)回复于 2006-06-01 21:49:44 得分 0
字符串要保存比较好办,但问题是现在要保存一个对象,请问怎么变换法?Top




