?
1
.數值應保存在二進制文件
首先列舉文本、二進制文件的操作(讀寫)方法:
方式
1
:
//
文本文件操作:創建
/
讀取
/
拷貝
/
刪除
using
System;
using System.IO;
class Test
{
???string path = @"f:\t.txt";
???publicstaticvoid Main()
???{ ??????
??????//
創建并寫入
(
將覆蓋已有文件
)
????? if (!File.Exists(path))
??????{
//StreamWriter m=new ??????????
//StreamWriter(path,true,Encoding.Default,1);//ASCII,1?? Encoding.Default
:即//UTF-8編碼? 這樣就可以指定編碼方式
????using (StreamWriter sw = File.CreateText(path))
?????????{
????????????sw.WriteLine("Hello");
?????????}
??????}
??????//
讀取文件
??????using (StreamReader sr = File.OpenText(path))
??????{
??????? string s = "";
????????while ((s = sr.ReadLine()) != null)
????????{
???????????Console.WriteLine(s);
????????}
?????}
?????//
刪除
/
拷貝
???? try
?????{
????????File.Delete(path);
????????File.Copy(path, @"f:\tt.txt");
?????}
?????catch (Exception e)
?????{
????????Console.WriteLine("The process failed: {0}", e.ToString());
?????}
???}
}
方式
2
:
//
流文件(二進制)操作
private const string name = "Test.data";
public static void Main(String[] args)
{
????//
打開文件
()??,
或通過
File
創建立如:
fs = File.Create(path, 1024)
????FileStream fs = new FileStream(name, FileMode.CreateNew);
????//
轉換為字節
寫入數據
(
可寫入中文
)
????Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
????//
字節數組
,
字節偏移量
,
最多寫入的字節數
BinaryWriter?? w?? =?? new?? BinaryWriter(fs);
//
設置要寫入的偏移量?
fs.Position=fs.Length;
??//??fs.Write(info, 0, info.Length);??
這個也可以
????w.Close();
????fs.Close();
????//
打開文件
????fs = new FileStream(name, FileMode.Open, FileAccess.Read);
????//
讀取
????BinaryReader r = new BinaryReader(fs);
????for (int i = 0; i < 11; i++)
????{
????????Console.WriteLine(r.ReadInt32());
????}
????w.Close();
????fs.Close();
在將一系列二進制數如方式
1
寫入到
file.txt(
二進制
)
文件后,打開
file.txt
后顯示的數據二進制數有些錯誤,有些正確。(與存入的不一樣)
向文件中寫入的
默認(也可以設置)
都是使用
UTF-8
編碼
。打開
file.txt
是也是默認
UTF-8
編碼。
?
若將其如方式
2
存入
二進制文件,則顯示的數據一致。若將二進制數(整數)保存為文本文件出錯。二進制文件是直接寫入文件的(磁盤)沒有經過編碼和讀取時的解碼。