using UnityEngine; using System.Collections; using System.Xml; using System; using System.Text; using System.IO; public class Weather : MonoBehaviour { XmlDocument xmlDoc; // Use this for initialization void Start () { xmlDoc = new XmlDocument (); StartCoroutine (DownXml ()); } // Update is called once per frame void Update () { } IEnumerator DownXml () { WWW www = new WWW ("http://flash.weather.com.cn/wmaps/xml/dalian.xml"); yield return www; CreateFile (Application.dataPath,"myXml.xml",www.text); } void CreateFile (string path,string name,string info) { // 文件流信息 StreamWriter sw; FileInfo t = new FileInfo (path + "//" + name); if (!t.Exists) { // 如果此文件不存在则创建 sw = t.CreateText (); // 以行的形式写入信息 sw.WriteLine (info); } else { // 如果此文件存在则打开 sw = t.AppendText (); } // 关闭流 sw.Close (); // 销毁流 sw.Dispose (); } void DeleteFile (string path,string name) { File.Delete (path + "//" + name); } }
代码中头文件需要注意一下,涉及到IO读取文件。创建文件、删除文件、读取文件的方法我也已经封装好,Start方法中为了避免上次保存文件的残留首先删除原来的文件,然后创建文件FileName.txt ,我们也可修改文件的类型的后缀名。这里我写的是.txt ,为了完整的让中文出现在IOS与Android中所以这里给文件中写的数据是”宣雨松MOMO”,最后在OnGUI中将读取文件的文本信息显示在屏幕中,脚本保存格式为UTF-16。 代码中我们保存文件的路径是Application.persistentDataPath。 如果你写的路径是 Application.dataPath在编辑器中是可以正常读取,但是在IOS与Android中是无法读取的,昨天问我的那个朋友就是因为这里路径写的有问题没能成功的写入文件。 Application.persistentDataPath路径就是将文件保存在手机的沙盒中,如果在编辑器中运行本程序文件将保存在Finder-》 资源库-》Caches-》你的工程-》保存的文件 。本例的路径就是 Finder->资源库-> Caches -> txt->FileName.txt。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。