- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class LessonTryCatch : MonoBehaviour {
- public GameObject obj;
- // Use this for initialization
- void Start () {
- Debug.Log("开始 try");
- try
- {
- Debug.Log("try 语句块!");
- Debug.Log(obj.name);// 这句话一定会报错, 跳转 catch
- Debug.Log("打印名字");
- }
- catch (System.Exception e)
- {
- Debug.Log("catch 语句块!" + e);
- Debug.Log("错误信息:" + e);
- Debug.Log(obj.name);// 如果 catch 报错, 之后的代码都不会执行
- }
- Debug.Log("结束 try");
- }
- // Update is called once per frame
- void Update () {
- }
- }
作业: 读取文本内容, 显示在 UI 的 text 组件上, 并实现内容滚动
文本位置调整
文本自动扩容
读取文件
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.IO;
- using System.Text;
- using UnityEngine.UI;
- public class LessonHomework : MonoBehaviour {
- public const string filePath = @"D:\ 桌面 \ 1.txt";
- private Text text;
- private void Awake()
- {
- text = transform.Find("Mask/Text").GetComponent<Text>();
- }
- // Use this for initialization
- void Start () {
- FileStream fs = File.Open(filePath, FileMode.Open);
- try
- {
- byte[] bytes = new byte[fs.Length];
- int ret = fs.Read(bytes, 0, (int)fs.Length);
- string str = Encoding.UTF8.GetString(bytes);
- text.text = str;
- }
- catch (System.Exception e)
- {
- Debug.Log(e.ToString());
- }
- fs.Close();
- }
- // Update is called once per frame
- void Update () {
- }
- }
写入文件
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.IO;
- using System.Text;
- public class LessonWriteFile : MonoBehaviour {
- public const string filePath = @"D:\ 桌面 \ Directory\ReadFile.txt";
- // Use this for initialization
- void Start () {
- //string filePath1 = Directory.GetCurrentDirectory();
- //filePath1 = filePath1 + "\\Directory\\";
- // 写入文本文件
- //1, 打开文件
- FileStream fs = File.Open(filePath, FileMode.Open);
- // FileStream fs = File.Open(filePath, FileMode.Append);// 追加模式
- Debug.Log("游标的位置:" + fs.Position);
- // 第一个参数: 向前移或向后移多少位, 第二个参数: 从什么位置开始移动
- // 对于想要把游标移动到文件的末尾
- // 方法 1
- fs.Seek(fs.Length, SeekOrigin.Begin);
- // 方法 2
- fs.Seek(fs.Length - fs.Position, SeekOrigin.Current);
- // 方法 3
- fs.Seek(0, SeekOrigin.End);
- // 对于想要把游标移动到文件的开始
- // 方法 1
- fs.Seek(0, SeekOrigin.Begin);
- // 方法 2
- fs.Seek(-fs.Position, SeekOrigin.Current);
- // 方法 3
- fs.Seek(-fs.Length, SeekOrigin.End);
- Debug.Log("游标的位置:" + fs.Position);
- // 为了保证文件打开之后一定能关闭, 文件操作写在 Try Catch 里
- try
- {
- //2, 把要写入的内容转成字节数组
- string str = "做一只快乐的小鱼苗~";
- byte[] bytes = Encoding.UTF8.GetBytes(str);
- //3, 写入文件
- // 第一个参数: 写入文件的内容转换成的字符串
- // 第二个参数: 从字节数组中的第几位开始写入
- // 第三个参数: 从字节数组中写入多少位
- fs.Write(bytes, 0, bytes.Length);
- }
- catch (System.Exception e)
- {
- Debug.Log(e.ToString());
- }
- // 最终关闭文件流
- fs.Close();
- }
- // Update is called once per frame
- void Update () {
- }
- }
文本读写器
文本读
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.IO;
- public class LessonStreamReader : MonoBehaviour {
- public const string filePath = @"D:\ 桌面 \ Directory\ReadFile.txt";
- // Use this for initialization
- void Start () {
- // 文本读写器
- // 打开文件, 保证路径是正确的, 有效的
- StreamReader sr = new StreamReader(filePath, System.Text.Encoding.UTF8);
- try
- {
- //string str = sr.ReadLine();// 只读取一行.
- string str = sr.ReadToEnd();// 从开始读到结尾
- Debug.Log("读取的内容:" + str);
- }
- catch (System.Exception e)
- {
- Debug.Log(e.ToString());
- }
- // 最后一定要关闭文件
- sr.Close();
- }
- // Update is called once per frame
- void Update () {
- }
- }
文本写, 不能操作游标, 如果不使用追加模式, 默认清空原有内容, 重新写入
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.IO;
- public class LessonStreamWrite : MonoBehaviour {
- public const string filePath = @"D:\ 桌面 \ Directory\ReadFile.txt";
- // Use this for initialization
- void Start () {
- // 文本读写器
- //1, 打开文件
- // 这个重载, 会把文件内容全部清除, 重新写入内容
- //StreamWriter sw = new StreamWriter(filePath);
- // 这个重载, 是追加模式, 第二个参数指定是否追加, 第三个参数是指定编码格式
- StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.UTF8);
- try
- {
- sw.Write("Hello World!");
- }
- catch (System.Exception e)
- {
- Debug.Log(e.ToString());
- }
- // 最后一定关闭文件
- sw.Close();
- }
- // Update is called once per frame
- void Update () {
- }
- }
文件拷贝
小文件的直接拷贝
大文件的线程拷贝
1, 使用多线程的方式, 防止文件过大, 卡死主线程
2, 多线程里面不能改变需要渲染操作的值 (例如改变 slider 的进度条的值)
3, 多线程里使用 while 循环, 要设置跳出循环的条件
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.IO;
- using System.Threading;
- public class LessonCopyFile : MonoBehaviour {
- public UnityEngine.UI.Slider slider;
- public const string sourceFilePath = @"D:\ 桌面 \ 1.rar";
- public const string targetFilePath = @"D:\ 桌面 \ 2.rar";
- private float maxValue = 1f;
- private float currentValue;
- private bool isStop = false;
- // Use this for initialization
- void Start () {
- // 小文件的拷贝
- //CopyFile(sourceFilePath, targetFilePath);
- // 大文件的拷贝
- //TestCopyFile();
- // 大文件的线程拷贝
- //1. 申请一个 Thread 的对象
- Thread th = new Thread(TestCopyFile);
- //2. 启动这个线程
- th.Start();
- }
- // Update is called once per frame
- void Update () {
- // 滑动条赋值
- slider.normalizedValue = currentValue / maxValue;
- }
- private void OnDestroy()
- {
- isStop = true;
- }
- // 小文件的拷贝
- void CopyFile(string sourceFile, string targetFile)
- {
- // 拷贝, 就把源文件的内容写入到新的文件中
- //1. 读取源文件的内容
- FileStream source = File.Open(sourceFile, FileMode.Open);
- byte[] bytes = new byte[source.Length];
- try
- {
- // 读取内容
- source.Read(bytes, 0, bytes.Length);
- }
- catch (System.Exception e)
- {
- Debug.Log(e.ToString());
- }
- source.Close();
- //2. 写入新文件
- FileStream target = File.Open(targetFile, FileMode.Create);
- try
- {
- // 写入新文件
- target.Write(bytes, 0, bytes.Length);
- }
- catch (System.Exception e)
- {
- Debug.Log(e.ToString());
- }
- target.Close();
- }
- void TestCopyFile()
- {
- Debug.Log("开始拷贝");
- CopyBigFile(sourceFilePath, targetFilePath);
- Debug.Log("拷贝结束");
- }
- void CopyBigFile(string sourceFile, string targetFile)
- {
- FileStream source = new FileStream(sourceFile, FileMode.Open);
- FileStream target = new FileStream(targetFile, FileMode.Create);
- byte[] bytes = new byte[100];// 限制每次拷贝 100 * 1024 个字节大小的内容
- maxValue = source.Length;
- try
- {
- long readCount = 0;
- // 必须保证所有的内容都写入到另一个文件中了, 跳出循环
- // 只要保证每次读取的长度的累加值 大于等于 文件流的大小
- while (readCount < source.Length)
- {
- int length = source.Read(bytes, 0, bytes.Length);
- target.Write(bytes, 0, length);
- readCount += length;
- currentValue = readCount;
- // 当组件销毁时, 停止多线程里的 while 循环, 防止程序停止运行时, 多线程仍在执行
- if (isStop)
- {
- break;
- }
- }
- }
- catch (System.Exception e)
- {
- Debug.Log(e.ToString());
- }
- source.Close();
- target.Close();
- }
- }
图片加载并显示 UI 组件中
方法一:
1, 把图片转换成字节数组
2, 把字节数组转换成图片, loadImage
方法二:
1, 本地加载, 加 file:\\
2, 网络加载, 使用协程
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.IO;
- using UnityEngine.UI;
- public class LessonLoadTexture : MonoBehaviour {
- public RawImage image;
- // Use this for initialization
- void Start () {
- image.texture = LoadFileTexture(@"D:\ 桌面 \ 1.jpg");
- image.SetNativeSize();
- // 加载网上的
- //StartCoroutine(LoadTexture(@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1527592090920&di=60ad08a7d15d3f91e7a370a9479b5d50&imgtype=0&src=http://image.yy.com/yywebalbumbs2bucket/fa63ba48c11f46278f9f2be98a141138_1499771837216.jpeg"));
- // 加载本地的 如果要 www 加载本地的图片, 那么在路径前要加 file://
- //StartCoroutine(LoadTexture(@"file://D:\ 桌面 \ 1.jpg"));
- }
- // Update is called once per frame
- void Update () {
- }
- Texture LoadFileTexture(string filePath)
- {
- // 把图片转换成字节数组
- FileStream fs = File.Open(filePath, FileMode.Open);
- byte[] bytes = new byte[fs.Length];
- try
- {
- fs.Read(bytes, 0, bytes.Length);
- }
- catch (System.Exception e)
- {
- Debug.Log(e.ToString());
- }
- fs.Close();
- // 把字节数组转换成图片
- Texture2D tex = new Texture2D(0, 0);
- if (tex.LoadImage(bytes))// 把从字节数组中加载图片
- {
- return tex;
- }
- else
- {
- return null;
- }
- }
- IEnumerator LoadTexture(string path)
- {
- WWW www = new WWW(path);
- yield return www;// 图片加载完成后, 在执行后面的步骤
- //string.IsNullOrEmpty(error) 判断 error 不能为 null 也不能为 ""
- if (www != null && string.IsNullOrEmpty(www.error))
- {
- image.texture = www.texture;
- image.SetNativeSize();
- }
- else
- {
- Debug.LogError("加载错误");
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2950881.html