Unity使用I/O数据流操作文件(读写文本、选择本地图片加载、选择文件并计算其大小)

工作开发中经常使用I/O数据流技术操作文件,包括读写文本,加载本地图片和其他文件等,这里我们使用I/O流很方便就能完成。通过本博客你就可以学习到如何使用I/O流操作文本啦!

简单搭建demo场景

在这里插入图片描述
1.用一个输入框(InputFiel组件)输入我们想要写入文本文件的内容,点击读取按钮的时候我们可以从文本文件里读取我们刚才写入的内容。
在这里插入图片描述
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;//txt文本文件路径

    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";//工程目录Assets文件下
	}

将输入框内容写入文本文件

/// <summary>
    /// 输入结束写入文本文件
    /// </summary>
    /// <param name="value"></param>
    private void OnInputEndEdit(string value)
    {
    
    
        if (!string.IsNullOrEmpty(value))
        {
    
    
            //写入方式一,如果文件unity.txt不存在,则创建改文件,并写入字符串
            FileStream fs = new FileStream(txtPath, FileMode.OpenOrCreate);//将在Assets下创建unity.txt文本文件
            StreamWriter writer = new StreamWriter(fs);
            writer.WriteLine(value);
            writer.Close();

            //写入方式二
            //File.WriteAllText(txtPath, readText.text);

            print("写入完毕");
        }
    }

读取文本文件内容并显示

/// <summary>
    /// 读取文本文件
    /// </summary>
    private void OnReadBtnClick()
    {
    
    
        if (File.Exists(txtPath))
        {
    
    
            //读取方式一
            //StreamReader sr = new StreamReader(txtPath);
            //readText.text = sr.ReadToEnd();
            //sr.Close();

            readText.text = File.ReadAllText(txtPath);//读取方式二
        }
    }

选择本地图片加载并显示

/// <summary>
    /// 选择一张图片加载赋值给img
    /// </summary>
    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);//读取图片字节块写入指定的缓冲区imgBytes
            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;
        }
    }

选择本地模型并计算其文件大小

/// <summary>
    /// 计算模型文件大小
    /// </summary>
    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);
        }
    }

注意事项及其他知识点

在这里插入图片描述

demo演示效果

  • 读写文本
    请添加图片描述
    在这里插入图片描述

  • 选择图片
    请添加图片描述

  • 选择模型

请添加图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42437783/article/details/124535862