纳金网
标题:
读取和写入文本文件的方法
[打印本页]
作者:
王者再临
时间:
2014-10-20 00:36
标题:
读取和写入文本文件的方法
读取和写入文本文件可以用unity自带的类,也可以用C#原生提供的。
1.unity自带的TextAsset:
TextAsset test = (TextAsset)Resources.Load("xxxx");
string temp = test.text;
2,使用C#文件流加载外部文本文件:
(1)先构造一个可以读取和写入的类
using System;
using System.IO;
public class FileReadWriteManager
{
public void WriteTextFile(string pathAndName,string stringData)
{
FileInfo textFile=new FileInfo(pathAndName);
if(textFile.Exists)
textFile.Delete();
StreamWriter writer;
writer=textFile.CreateText();
writer.Write(stringData);
writer.Close();
}
public string ReadTextFile(string pathAndName)
{
string dataAsString="";
try{
StreamReader textReader=File.OpenText(pathAndName);
dataAsString=textReader.ReadToEnd();
textReader.Close();
}
catch(Exception e)
{
Debug.Log("xxxx");
}
return dataAsString;
}
}
(2)在unity中使用调用读文件
using UnityEngine;
using System.Collections;
using System.IO;
public class test : MonoBehaviour {
string filePath = "";
string text = "";
FileReadWriteManager file = new FileReadWriteManager();
void Start () {
string fileName = "xx.txt";
filePath = Path.Combine(Application.dataPath,"Resources");
filePath = Path.Combine(filePath, fileName);
text = file.ReadTextFile(filePath);
}
}
(3)在unity中使用,调用写文件
FileReadWriteManager file = new FileReadWriteManager();
filePath=Application.dataPath+Path.DirectorySeparatorChar+fileName;
string text="Hello";
file.WriteTextFile(filePath,text);
Tips: 使用Path.Combine(Application.dataPath,"Resources");来代替斜杠可以避免很多问题。
[url=]Path[/url]
.DirectorySeparatorChar 目录分隔符
默认字符用于分隔目录层次。(只读)
This is '\' on Windows and '/' on Mac OS X
Windows用"\",Mac OS用"/"。
作者:
hyui
时间:
2014-10-20 01:06
Good to learn from code!
作者:
cgjch8
时间:
2014-10-20 08:45
Good to learn
作者:
HIDEOKOJIMA
时间:
2014-10-20 10:22
Thanks for sharing this !
欢迎光临 纳金网 (http://old.narkii.com/club/)
Powered by Discuz! X2.5