1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
| #region 1.打开或创建指定文件
FileStream fs = new FileStream(PeresistentURL("TestNew.Test"), FileMode.OpenOrCreate, FileAccess.ReadWrite);
FileStream fs1 = File.Open(PeresistentURL("TestNew1.Test"), FileMode.Open); fs1.Close(); fs1.Dispose();
FileStream fs2 = File.Create(PeresistentURL("TestNew1.Test"), 2048); fs2.Close(); fs2.Dispose(); #endregion
#region 2.属性方法
if (fs.CanRead) { }
if (fs.CanWrite) { }
fs.Flush();
fs.Close();
fs.Dispose(); #endregion
#region 3.写入字节
using (fs = new FileStream(PeresistentURL("TestNew.Test"), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { byte[] bytes = BitConverter.GetBytes(1 << 8); fs.Write(bytes, 0, bytes.Length);
bytes = Encoding.UTF8.GetBytes("hello world"); byte[] length = BitConverter.GetBytes(bytes.Length); fs.Write(length, 0, length.Length); fs.Write(bytes, 0, bytes.Length);
fs.Flush(); fs.Close(); };
#endregion
#region 4.读取字节
using (fs = File.Open(PeresistentURL("TestNew.Test"), FileMode.Open, FileAccess.Read)) { byte[] bytes2 = new byte[4]; int index = fs.Read(bytes2, 0, 4); int i = BitConverter.ToInt32(bytes2, 0); print("取出来的第一个整数" + i); print("索引向前移动" + index + "个位置");
index = fs.Read(bytes2, 0, 4); print("索引向前移动" + index + "个位置"); int length1 = BitConverter.ToInt32(bytes2, 0); bytes2 = new byte[length1]; index = fs.Read(bytes2, 0, length1); print("索引向前移动" + index + "个位置"); print(Encoding.UTF8.GetString(bytes2));
fs.Flush(); fs.Close(); }
using (fs = File.Open(PeresistentURL("/TestNew.Test"), FileMode.Open)) { print("============================="); byte[] bytes3 = new byte[fs.Length]; fs.Read(bytes3, 0, bytes3.Length); fs.Dispose(); print(BitConverter.ToInt32(bytes3, 0)); int length2 = BitConverter.ToInt32(bytes3, 4); print(Encoding.UTF8.GetString(bytes3, 8, length2)); } #endregion
#region 知识点三更加安全的使用文件流对象
#endregion private String AssetURL(string url) { return Application.dataPath + "/" + url; }
private String PeresistentURL(string url) { print(Application.persistentDataPath + "/" + url); return Application.persistentDataPath + "/" + url; }
|