工作开发中经常使用I/O数据流技术操作文件,包括读写文本,加载本地图片和其他文件等,这里我们使用I/O流很方便就能完成。通过本博客你就可以学习到如何使用I/O流操作文本啦!
简单搭建demo场景
![在这里插入图片描述](https://img-blog.csdnimg.cn/ce50ff39d1ce4a00b400600f2b390449.png) 1.用一个输入框(InputFiel组件)输入我们想要写入文本文件的内容,点击读取按钮的时候我们可以从文本文件里读取我们刚才写入的内容。 ![在这里插入图片描述](https://img-blog.csdnimg.cn/3c4b2a799d5f43ac8575c41dc2916560.png) 2.点击选择一个模型按钮可以打开本地资源浏览器,当我们选择一个模型后,可以计算这个模型的大小并显示到Text上。 点击选择一张图片按钮可以打开本地资源浏览器,选择图片后加载并显示到Image上。
脚本实现I/O流操作文件
引用命名空间并定义UI组件
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using Crosstales.FB;
public class IOtest : MonoBehaviour
{
public InputField input;
private string txtPath;
public Text readText;
public Button readBtn;
public Image img;
public Button selectImgBtn;
public Button calculateBtn;
public Text calculateText;
}
在Start函数里为添加各个组件的监听方法
void Start ()
{
input.onEndEdit.AddListener(OnInputEndEdit);
readBtn.onClick.AddListener(OnReadBtnClick);
selectImgBtn.onClick.AddListener(OnSelectImgClick);
calculateBtn.onClick.AddListener(OnCalculateClick);
txtPath = Application.dataPath + "/unity.txt";
}
将输入框内容写入文本文件
private void OnInputEndEdit(string value)
{
if (!string.IsNullOrEmpty(value))
{
FileStream fs = new FileStream(txtPath, FileMode.OpenOrCreate);
StreamWriter writer = new StreamWriter(fs);
writer.WriteLine(value);
writer.Close();
print("写入完毕");
}
}
读取文本文件内容并显示
private void OnReadBtnClick()
{
if (File.Exists(txtPath))
{
readText.text = File.ReadAllText(txtPath);
}
}
选择本地图片加载并显示
private void OnSelectImgClick()
{
ExtensionFilter[] eFilters = new ExtensionFilter[1];
eFilters[0] = new ExtensionFilter("图片格式", "png", "jpg");
string imgPath = FileBrowser.OpenSingleFile("请选择一张图片", "", eFilters);
if (File.Exists(imgPath))
{
FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
byte[] imgBytes = new byte[fs.Length];
fs.Read(imgBytes, 0, imgBytes.Length);
fs.Close();
fs.Dispose();
Texture2D tex = new Texture2D(10, 10);
tex.LoadImage(imgBytes);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.zero);
img.sprite = sprite;
}
}
选择本地模型并计算其文件大小
private void OnCalculateClick()
{
string extension = "fbx";
string fbxPath = FileBrowser.OpenSingleFile("请选择一个模型", "", extension);
string fbxName = Path.GetFileName(fbxPath);
if (File.Exists(fbxPath))
{
FileStream fs = new FileStream(fbxPath, FileMode.Open, FileAccess.Read);
byte[] fbxBytes = File.ReadAllBytes(fbxPath);
calculateText.text = string.Format("你打开的文件是:{0},共{1}字节,{2}kb,{3}M", fbxName, fbxBytes.Length, fbxBytes.Length / 1024, (fbxBytes.Length / 1024.0 / 1024.0).ToString("f2"));
print(fbxBytes.Length / 1024 / 1024);
}
}
注意事项及其他知识点
![在这里插入图片描述](https://img-blog.csdnimg.cn/521db9eaaf4143a09873144285b79ba8.png)
demo演示效果
![请添加图片描述](https://img-blog.csdnimg.cn/871d673d4bbd4bb0a4ed26efc7d53f85.gif) ![在这里插入图片描述](https://img-blog.csdnimg.cn/677662b1ca364b31bec3417b99f67a92.png)
|