Unity文件IO

本文深入探讨了文件系统和IO操作的基础知识,包括如何使用C#中的System.IO类库进行文件和目录的创建、读取、写入、复制、移动和删除等操作。同时,文章还介绍了数据流IO的概念,以及如何利用FileStream、StreamReader和StreamWriter进行数据的读写。最后,文中还提供了一个读取配置文件的例子,展示了如何解析和存储配置文件中的信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件系统与IO
文件系统对应类 System.IO
DriveInfo : 有关驱动器信息的类
主要方法:GetDrives 用于取得本计算机中所有驱动器信息对象
File: 有关对文件整体操作及内容读写的类
整体操作:

Create :创建文件
Delete: 删除文件
Move:移动文件(剪切)
Copy: 复制文件
Exists: 检查设备中是否有该文件
读写文件:
ReadAllText : 一次将文件中所有内容读入内存,并转为字符串
ReadAllLines: 一次将文件中所有内容读入内存,转为字符串,将字符串按行形成一个字符串数组
ReadLines: 并不会主动文件中的内容,只有再迭代时才读一行,每迭代一次向下读一行.
ReadAllBytes: 将文件中的内容一次读入内存,以字节数组的方式保存

WriteAllText: 一次写入大段文本。
WriteAllLines: 每写一行之后写一个换行符.
WriteAllBytes: 一次写入大量字节

FileInfo : 有关对文件整体操作及内容读写的类
与File不同的地方:比File类多一个Length属性,通过该属性可以了解一个文件所占有字节
Directory :有关对文件夹整体操作的类

常用方法:
CreateDirectory:创建文件夹
Delete:删除文件夹
Move:移动文件夹(不能跨驱动器移动)
GetFiles: 取得文件夹下所有的文件名
GetDirectoies:取得文件夹下所有的子文件夹名
Exists:检查某文件夹在设备中是否存在

DirectoryInfo 功能同Directory,只是所有成员为实例成员
Path类,专用于对路径字符串的处理

常用方法:
GetFileName :取得文件名及扩展名
GetFileNameWithOutExtension: 取得文件名不要扩展名
GetDirectoryName : 取得路径中目录的名称
Combine: 将多个字符串合并成为一个路径
/// <summary>
/// 文件夹处理
/// </summary>
public class DirectoryTest : MonoBehaviour
{
    //在D盘创建文件夹
    private string myPath = @"D:/aa/bb";
    private void Start(){
        DirectoryInfo info = new DirectoryInfo(myPath);
        //判断路径中是否有文件夹
        if (!info.Exists)
            info.Create();
        //if (info.Exists)
         //   info.Delete(true);
        string myPath02 = Path.Combine(myPath, @"cc");//@"D:/aa/bb/cc"
        DirectoryInfo info02 = new DirectoryInfo(myPath02);
        if (!info02.Exists)
            info02.Create();
        if (info02.Exists)
            info.Delete(true);
        /*
        if (!Directory.Exists(myPath))
            Directory.CreateDirectory(myPath);
        if (Directory.Exists(myPath))
            Directory.Delete(myPath);
         */
    }
}

    private string filePath = @"D:/Directory/file01.txt";
    private void Start()
    {
        //1.在D盘创建一个名字为Directory的文件夹,并创建一个file01.txt文件。
        string dirPath = Path.GetDirectoryName(filePath);
        if (!Directory.Exists(dirPath))
            Directory.CreateDirectory(dirPath);
        if (!File.Exists(filePath))
            File.Create(filePath);
        //2.(先在D盘放一个file02.txt文件)判断若存在,复制到D盘Directory文件夹下。
        if (File.Exists(@"D:/file02.txt"))
            File.Copy(@"D:/file02.txt", @"D:/Directory/file02.txt", true);
        //3.(先在D盘放一个Directory02文件夹,并创建几个子文件夹)
        //通过脚本打印出D盘Directory02文件夹下所有子文件夹的目录名
        string[] path = Directory.GetDirectories(@"D:/Directory02");
        foreach (var dirName in path)
        {
            print(dirName);
        }
    }

/// <summary>
/// 文件读写
/// </summary>
public class FileTest02 : MonoBehaviour
{
    private string filePath = @"D:/File.txt";
    private void Start()
    {
        //File.WriteAllText(filePath, " Hello aaaaaaa");//写入一大段文本内容
        //File.WriteAllLines(filePath, new string[] { "Hello", "Hi~", "hhhh" });
        //string file = File.ReadAllText(filePath);//读取一大段文本内容
        string[] file = File.ReadAllLines(filePath);
        foreach(string read in file)
        {
            print("读到的内容 : " + read);
        }
    }
 
}


/// <summary>
/// 文件处理
/// </summary>
public class FileTest : MonoBehaviour
{
    private string filePath = @"D:/aa/bb/test.txt";//文件路径
    private string filePathTo = @"E:/cc";
    private void Start(){
        //取得路径中目录的名称
        string dirPath = Path.GetDirectoryName(filePath);
        if (!Directory.Exists(dirPath))
            Directory.CreateDirectory(dirPath);
        if (!File.Exists(filePath))
            File.Create(filePath);
        //剪切文件 新路径:@"E:/cc/test.txt"
        string newFilePath = Path.Combine(filePathTo
            ,Path.GetFileName(filePath));
        if (!Directory.Exists(filePathTo))
            Directory.CreateDirectory(filePathTo);
        if (!File.Exists(newFilePath))
            File.Move(filePath, newFilePath);

    }
 
}

数据流 IO:Stream

流涉及三个基本操作:
1.	可以读取流(Read)。读取是从流到数据结构(如字节数组)的数据传输。
2.	可以写入流(Write)。写入是从数据结构到流的数据传输。
3.	流可以支持查找(Seek、Position)。查找是对流内的当前位置进行的查询和修改。查找功能取决于流具有的后备存储区类型。例如,网络流没有当前位置的统一概念,因此一般不支持查找。
FileStream FileMode
StreamReader:流内容读取器
	用于对数据流或本地文件简单的以字符的方式进行读取,
	常用方法:ReadLine Read ReadToEnd
StreamWriter:将内容写入流,写入器
	用于对数据流或本地文件简单的以字符的方式进行写入,
	常用方法:Write WriteLine
public class StreamTest : MonoBehaviour
{
    private string path = @"D:/Stream.txt";
    private string text = null;
    private void OnGUI()
    {
        if (GUILayout.Button("读取内容"))
            text = ReadFunc(path);
        GUILayout.Label("内容 : " + text);
    }
    private string ReadFunc(string filePath)
    {
        //创建流对象
        Stream stream = new FileStream(path, FileMode.Open);
        byte[] data = new byte[stream.Length];
        //读取流中所有字节
        stream.Read(data, 0, (int)stream.Length);
        //写入文件
        stream.Write(data, 0, (int)stream.Length);
        stream.Flush();//写完内容,需刷新
        //流用完需要关闭,否则资源得不到释放
        stream.Close();
        //解码
        return Encoding.UTF8.GetString(data);
    }
 
}

读取配置文件

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

/// <summary>
/// 读取配置文件
/// </summary>
public class ConfigTest : MonoBehaviour
{
    private Dictionary<string, Dictionary<string, string>> dic
     = new Dictionary<string, Dictionary<string, string>>();
    private string path;
    private void Start()
    {
        //读取StreamingAssets文件下的文件路径
         path = Path.Combine(Application.streamingAssetsPath,
            "Config.txt");
        LoadConfig();
    }
    //读取所有数据
    private void LoadConfig()
    {
        string[] lines = null;
        if (File.Exists(path))
        {
            lines = File.ReadAllLines(path);
            BuildDic(lines);
        }
    }
    //处理所有数据
    private void BuildDic(string[] lines)
    {
        //主键
        string mainKey = null;
       //子键
        string subKey = null;
        //值
        string subValue = null;
        foreach (var item in lines)
        {
            string line = null;
            line = item.Trim();//去除空行
            if (!string.IsNullOrEmpty(line))
            {
                //取主键
                if (line.StartsWith("["))
                {
                    mainKey = line.Substring(1, line.IndexOf("]") - 1);
                    dic.Add(mainKey, new Dictionary<string, string>());
                }
                //取子键以及值
                else
                {
                    var configValue = line.Split('=');
                    subKey = configValue[0].Trim();
                    subValue = configValue[1].Trim();
                    subValue = subValue.StartsWith("\"") ? subValue.Substring(1) : subValue;
                    dic[mainKey].Add(subKey, subValue);
                }
            }
        }
    }
    private void OnGUI()
    {
        GUILayout.Label(dic["Login"]["Password"]);
    }
}


//配置文件内容
[Game]  
Version=1

[Login]
Account = 账号不输入,怎么给你保存数据呀
Password = 没有密码,无法进入游戏
Success = 账号注册成功,赶紧登陆游戏爽去吧
Faild = 账号创建失败,赶快重新创建去吧,一会服务器满了,你就不能和其他小伙伴愉快玩耍啦
Successful = 登陆成功
LoginFaild = 账号或密码错误,请重新输入!!!

[Job]
Job1 = 战士
Job2 = 法师
Description1 = "    具有强大的近战攻击力,一直活跃在战斗的最前方。强大的力量和充沛的体力让他可以摧毁敌人的一切防御。(推荐新手使用)
Description2 = "    将所有的精力都用在魔法奥义上,每当他向空中举手的时候,不可预测的灾难即将到来。由于自身体力较弱,法师靠法术远距离攻打敌人。
Weapon1 = 砍刀
Weapon2 = 法杖

[Money]
Gold = 100
Diamond = 11.2

[Scene]
LoadFailed = 场景加载失败,重新加载~



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值