UNITY3D使(shǐ)用C#脚本的几种读写TXT文本文件的方法
2019/11/12 点击(jī):
//注(zhù)意:要读取的文本文件TXT的编码类型要为(wéi)utf-8,不然会出现(xiàn)中文乱码或者直接不显示,如果是其(qí)它编码方式可以把文件
//另保存为(wéi)UTF-8的格式
using UnityEngine;
using System.Collections;
using System.IO;//用法三的时候需要定义这个
using System.Text;//法(fǎ)二的时候需要使用定义(yì)这(zhè)个
public class GUTexture : MonoBehaviour {
GUIText m_GUIText;
public TextAsset m_TextAsset; //法(fǎ)一 ,这个需要在unity编辑器(qì)进行赋值,把.txt文本文件保存在Asset下的 Resources文件夹下,然后把.txt文件拖拽过来进(jìn)行赋值
TextAsset m_TextAsset1;
string m_Str;
string m_FileName; //法二要用
string[] strs; //法二要用
void Start () {
m_GUIText = gameObject.GetComponent(); //找到该游戏物体的GUIText组件,用来显示读取到 的文本
m_FileName = "Z800虚(xū)拟头盔说明书链接UTF-8.txt"; //法二要用(yòng),要读取的文(wén)件名,这个是相对路径
}
//鼠(shǔ)标进入(rù)该游戏物体执行(háng)
void OnMouseEnter() {
m_GUIText.text = Resources.Load("Z800虚拟(nǐ)头盔说(shuō)明书链接").text;//法一,需要把文(wén)本文件保(bǎo)存(cún)在Asset文 件夹下的(de)Resources文件(jiàn)夹内
// ReadFile(m_FileName);//法二
//m_GUIText.text = m_Str;//把读取到的内容放到GUIText组件中显示 // Read();//法三
//m_GUIText.text =m_Str;//把读取到的内容放到GUIText组件中显示
}
//方法二:通过ReadFile(名字自(zì)己定义)方法来(lái)读取,传(chuán)入的(de)是文件路径
void ReadFile(string FileName) {
strs = File.ReadAllLines(FileName);//读取文件的所有行,并将数据读取到(dào)定义好的(de)字符数组strs中(zhōng),一行存一个单元
for (int i = 0; i < strs.Length; i++)
{
m_Str += strs[i];//读取每一(yī)行,并连起来
m_Str += "\n";//每一行末尾换行
}
}
//方法三: 下面这个是通过文件流来读(dú)取txt文件的方(fāng)法
public void Read()
{
try
{
string pathSource = m_FileName;
using (FileStream fsSource = new FileStream(pathSource,
FileMode.Open, FileAccess.Read))
{
// Read the source file into a byte array.
byte[] bytes = new byte[fsSource.Length];
int numBytesToRead = (int)fsSource.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
numBytesToRead = bytes.Length;
//text = Encoding.Default.GetString(bytes);
m_Str= UTF8Encoding.UTF8.GetString(bytes);
}
}
catch
{
//ioEx.Message
}
} //法四
using System.IO;
using System.Text;
Debug.Log(File.ReadAllText("C:\\Users\\zhang\\Desktop\\wiseglove数据手套录制数据.txt", Encoding.Default)); // ReadAllText方法第一个参数是要读取txt文件的路径(jìng),第二个参数(shù)是编码方式,这里采用默认
//一种(zhǒng)以追加的方式写(xiě)入txt方法
using System.IO;
using System.Text;
File.AppendAllText("C:\\Users\\zxy\\Desktop\\wiseglove数据手套录制数据.txt", "我被写进来了(le)",Encoding.Default);
//第一个参数是要写入的文件路径,第二个参(cān)数是要写入(rù)的文本,第三个参(cān)数是编码方式
}
- 上一篇:unity3d读写EXCEL文件的方法 2019/11/12
- 下一(yī)篇:Intel RealSense D435i 3D面部和动作捕 2019/11/11
