读取和保存txt文件
来源:互联网 发布:淘宝加入购物车看不到 编辑:程序博客网 时间:2024/04/19 21:01
涉及知识点
- 读取文件内容;
- 创建文件夹和文件,并写入内容;
- 以覆盖的方式写入内容,以添加的方式写入内容;
读取和保存txt文件源码
using UnityEngine;
using System.Text.RegularExpressions;using System;
using System.Net;
using System.Text;
using System.Threading;
using System.IO;
using UnityEngine.UI;
public class ReadAndSaveText : MonoBehaviour
{
public InputField input;
public Toggle isAdd;
public Text showSaveData;
public Text showReadData;
private WebClient myWebClient = new WebClient();
private string url = "http://www.163.com";
private string userDocPath;
private string directory;
private string filePath;
protected void Start()
{
#if UNITY_STANDALONE_LINUX
userDocPath = Environment.GetEnvironmentVariable("HOME");//home目录
#elif UNITY_STANDALONE_WIN
userDocPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//文档目录
#endif
directory = userDocPath + "/.Test";
filePath = directory + "/Test.txt";
Debug.Log("Save data directory: " + directory);
}
public void ReadData()
{
string readData = null;
if (Directory.Exists(directory) && File.Exists(filePath))
{
using (StreamReader read = new StreamReader(filePath, Encoding.Default))
{
readData = read.ReadToEnd();
}
}
showReadData.text = "读取内容:\n" + readData;
}
public void SaveData()
{
string data = input.text;
Debug.Log("Saving data file.");
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
if (!File.Exists(filePath))
{
Debug.Log("Creating new data file.");
//创建文件并写入内容,同时换行
FileStream fs = new FileStream(filePath, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(data);
sw.Flush();
sw.Close();
fs.Close();
showSaveData.text += "\n" + data;
}
else
{
if (!isAdd.isOn)
{
//覆盖内容,同时换行
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.WriteLine(data);
}
showSaveData.text = "保存内容:\n" + data;
}
else
{
//在已有的文本后添加新的内容,同时换行
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine(data);
}
showSaveData.text += "\n" + data;
}
}
Debug.Log("Save data success.");
}
}
文章仅供学习和参考!如有错误请指正!
阅读全文
0 0
- 读取和保存txt文件
- Matlab读取和保存TXT文件数据
- vb读取保存txt文件
- Android保存读取txt文件
- 保存和读取文件
- 文件保存和读取
- 文件保存和读取
- 文件保存和读取
- Javascript写入txt和读取txt文件
- Javascript写入txt和读取txt文件
- Javascript写入txt和读取txt文件
- Javascript写入txt和读取txt文件
- QT和VS读取.txt文件中的数据并保存为数组
- Qt中QDomDocument,读取txt文件和xml文件,并且修改xml文件和保存修改后的文件
- java 读取txt文件和xls文件
- 简单打开和保存txt文件
- java读取TXT文件保存到数据库中
- qt 读取txt文件内容并保存到数组中
- help VS man VS info
- 合并两链表
- 数据类型转换之 QString与binary
- 不放过任何一个获客机会 自助餐如何做好小程序?
- HDU 4311 Meeting point-1 (思维)
- 读取和保存txt文件
- SDWebImage如何避免复用
- linux grep命令使用详解
- 思维体操: HDU1049Climbing Worm
- mongdb之集合基本操作
- java面试题
- PAT 1012. The Best Rank (25)
- 基于.Net的软件部门的建设(建设中)
- oracle导入导出数据