继续上一节,继续读写代码的编写。
@H_404_3@
为了简化操作,所有的Encoding均采用Encoding.Default。
@H_404_3@
读取方法3;
@H_404_3@
Private Sub readText3(ByVal filename As String) Dim textContent As String Dim sr As New StreamReader(filename,Encoding.Default) Do textContent = sr.ReadLine() If IsNothing(textContent) Then Exit Do txtFile.Text &= textContent & ControlChars.CrLf Loop While True sr.Close() End Sub@H_404_3@
写入方法3:
Private Sub writeText3(ByVal filename As String) Dim textContent As String = txtFile.Text Dim sw As New StreamWriter(filename,False) Dim arrTextContent() As String = textContent.Split(ControlChars.CrLf) For i As Integer = 0 To arrTextContent.Length - 1 sw.WriteLine(arrTextContent(i)) Next sw.Close() End Sub使用时会发现,最后多写了一个回车。因为使用split的时候最后一个ControlChars.CrLf多带来了一个空字符串。请自行改正。
@H_404_3@
@H_404_3@
读取方法4:
先使用FileStream指定打开方式打开文件并读入文件流
@H_404_3@ 再使用StreamReader(参数1:文件流,参数2:编码格式)
@H_404_3@ 读取方式:将文本读入字符数组,然后将字符数组还原为字符串
Private Sub readText4(ByVal filename As String) Dim textContent As String Dim buffer() As Char Dim lenRead As Long Dim fs As New FileStream(filename,FileMode.OpenOrCreate,FileAccess.Read) lenRead = fs.Length Dim sr As New StreamReader(fs,Encoding.Default) ReDim buffer(lenRead - 1) sr.Read(buffer,lenRead) sr.Close() fs.Close() textContent = New String(buffer) txtFile.Text = textContent End Sub@H_404_3@
@H_404_3@
写入方法4:
先使用FileStream指定打开方式打开文件并读入文件流
@H_404_3@ 再使用StreamWriter(参数1:文件流,参数2:编码格式)
@H_404_3@ 写入方式:获得流长度,向流长度大小的缓冲一次性写入所有文本
Private Sub writeText4(ByVal filename As String) Dim textContent As String = txtFile.Text Dim lenWrite As Long Dim fs As New FileStream(filename,FileAccess.ReadWrite) lenWrite = textContent.Length Dim sw As New StreamWriter(fs,Encoding.Default,lenWrite - 1) sw.WriteLine(textContent) sw.Close() fs.Close() End Sub
@H_404_3@
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看 vb.net 教程 目录
原文链接:https://www.f2er.com/vb/256531.html