zoukankan      html  css  js  c++  java
  • 文件系统: 文本的读写, 二进制的读写, 流的读写, 最近访问列表和未来访问列表

    演示如何读写文本数据

    • 演示如何读写二进制数据
    • 演示如何读写流数据
    • 演示如何读写“最近访问列表”和“未来访问列表”

    1、演示如何读写文本数据

    <StackPanel Margin="0,50 ">


                <Button Name="btnWriteText" Content="Text方式写入文件" Click="btnWriteText_Click" Margin="5"></Button>
                <Button Name="btnReadText" Content="Text方式读取文件" Click="btnReadText_Click" Margin="5"></Button>
           
                <TextBlock Name="lblMsg" Margin="5"></TextBlock>
          
                
            </StackPanel>


    FileSystem/ReadWriteText.xaml.cs

    复制代码
    /*
     * 演示如何读写文本数据
     * 注:如果需要读写某扩展名的文件,需要在 Package.appxmanifest 增加“文件类型关联”声明,并做相应的配置
     * 
     * StorageFolder - 文件夹操作类
     *     获取文件夹相关属性、重命名、Create...、Get...等
     * 
     * StorageFile - 文件操作类
     *     获取文件相关属性、重命名、Create...、Get...、Copy...、Move...、Delete...、Open...、Replace...等
     *     
     * FileIO - 用于读写 IStorageFile 对象的帮助类
     *     WriteTextAsync() - 将指定的文本数据写入到指定的文件
     *     AppendTextAsync() - 将指定的文本数据追加到指定的文件
     *     WriteLinesAsync() - 将指定的多行文本数据写入到指定的文件
     *     AppendLinesAsync() - 将指定的多行文本数据追加到指定的文件
     *     ReadTextAsync() - 获取指定的文件中的文本数据
     *     ReadLinesAsync() - 获取指定的文件中的文本数据,返回的是一行一行的数据
     *     
     * 注:WinRT 中的关于存储操作的相关类都在 Windows.Storage 命名空间内
     */
    
    using System;
    using Windows.Storage;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    
    namespace XamlDemo.FileSystem
    {
        public sealed partial class ReadWriteText : Page
        {
            public ReadWriteText()
            {
                this.InitializeComponent();
            }

    private async void btnWriteText_Click(object sender, RoutedEventArgs e)
            {
                //在指定的目录下创建指定的文件
                StorageFolder storageFolder = KnownFolders.PicturesLibrary;// KnownFolders.DocumentsLibrary;
                StorageFile storageFile = await storageFolder.CreateFileAsync("abc.txt",CreationCollisionOption.ReplaceExisting);

                //在指定的文件中写入指定的文本
                string textContent = "I am wangma";
                await FileIO.WriteTextAsync(storageFile,textContent,UnicodeEncoding.Utf8);

                lblMsg.Text = "写入成功";
            }

            private async void btnReadText_Click(object sender, RoutedEventArgs e)
            {
                //在指定的目录下获取指定的文件
                StorageFolder storageFolder = KnownFolders.PicturesLibrary;
                try
                {
                    StorageFile storageFile = await storageFolder.GetFileAsync("abc.txt");
                    if (storageFile != null)
                    {
                        //获取指定的文件中的文本内容
                        string textContent = await FileIO.ReadTextAsync(storageFile, UnicodeEncoding.Utf8);
                        lblMsg.Text = "读取结果:" + textContent;
                    }
                }
                catch(Exception ex)
                {
                    lblMsg.Text = "读取失败:" + ex;
                }
              
            }

        }
    }
    复制代码


    2、演示如何读写二进制数据

     <StackPanel Margin="0 50">

                <Button Name="btnWriteBinary" Content="Binary方式写入" Margin="5" Click="btnWriteBinary_Click"></Button>
                <Button Name="btnReadBinary" Content="Binary方式读取" Margin="5" Click="btnReadBinary_Click"></Button>
                <TextBlock Name="lblMsg" Margin="5"></TextBlock>       
            </StackPanel>


    FileSystem/ReadWriteBinary.xaml.cs

    复制代码
    /*
     * 演示如何读写二进制数据
     * 注:如果需要读写某扩展名的文件,需要在 Package.appxmanifest 增加“文件类型关联”声明,并做相应的配置
     * 
     * StorageFolder - 文件夹操作类
     *     获取文件夹相关属性、重命名、Create...、Get...等
     * 
     * StorageFile - 文件操作类
     *     获取文件相关属性、重命名、Create...、Get...、Copy...、Move...、Delete...、Open...、Replace...等
     *     
     * FileIO - 用于读写 IStorageFile 对象的帮助类
     *     WriteBufferAsync() - 将指定的二进制数据写入指定的文件
     *     ReadBufferAsync() - 获取指定的文件中的二进制数据
     *     
     * IBuffer - WinRT 中的字节数组
     *     
     * 注:WinRT 中的关于存储操作的相关类都在 Windows.Storage 命名空间内
     */
    
    using System;
    using Windows.Storage;
    using Windows.Storage.Streams;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    
    namespace XamlDemo.FileSystem
    {
        public sealed partial class ReadWriteBinary : Page
        {
            public ReadWriteBinary()
            {
                this.InitializeComponent();
            }

    private async void btnWriteBinary_Click(object sender, RoutedEventArgs e)
            {
                //在指定的目录下创建指定的文件
                StorageFolder storageFolder = KnownFolders.PicturesLibrary;
                StorageFile storageFile =await storageFolder.CreateFileAsync("xyz.txt",CreationCollisionOption.ReplaceExisting);

                //将字符串转换成二进制数据,并保存到指定文件
                string textContent = "helllollllllllllllll";
                InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();
                DataWriter dataWriter = new DataWriter(memoryStream);
                dataWriter.WriteString(textContent);
                IBuffer buffer = dataWriter.DetachBuffer();
                await FileIO.WriteBufferAsync(storageFile,buffer);

                lblMsg.Text = "写入成功";
            }

            private async void btnReadBinary_Click(object sender, RoutedEventArgs e)
            {
                //在指定的目录下获取指定的文件
                StorageFolder storageFolder = KnownFolders.PicturesLibrary;
                try
                {
                    StorageFile storageFile = await storageFolder.GetFileAsync("xyz.txt");
                    if (storageFile != null)
                    {
                        //获取指定文件中的二进制数据,将其转换成字符串并显示
                        IBuffer buffer = await FileIO.ReadBufferAsync(storageFile);
                        DataReader dataReader = DataReader.FromBuffer(buffer);
                        string textContent = dataReader.ReadString(buffer.Length);

                        lblMsg.Text = "读取结果:" + textContent;
                    }
                }
                catch(Exception ex)
                {
                    lblMsg.Text = "读取失败:" + ex;
                }

            }

        }
    }
    复制代码


    3、演示如何读写流数据

    <StackPanel Margin="0 50">


                <Button Name="btnWrteStream" Content="Stream方式写入" Click="btnWrteStream_Click" Margin="5"></Button>
                <Button Name="btnReadStream" Content="Stream方式读取" Click="btnReadStream_Click" Margin="5"></Button>
                <TextBlock Name="lblMsg" Margin="5"></TextBlock>

            </StackPanel>


    FileSystem/ReadWriteStream.xaml.cs

    复制代码
    /*
     * 演示如何读写流数据
     * 注:如果需要读写某扩展名的文件,需要在 Package.appxmanifest 增加“文件类型关联”声明,并做相应的配置
     * 
     * StorageFolder - 文件夹操作类
     *     获取文件夹相关属性、重命名、Create...、Get...等
     * 
     * StorageFile - 文件操作类
     *     获取文件相关属性、重命名、Create...、Get...、Copy...、Move...、Delete...、Open...、Replace...等
     *     
     * IBuffer - WinRT 中的字节数组
     * 
     * IInputStream - 需要读取的流
     * IOutputStream - 需要写入的流
     * IRandomAccessStream - 需要读取、写入的流,其继承自 IInputStream 和 IOutputStream
     * 
     * DataReader - 从数据流中读取数据,即从 IInputStream 读取
     *     LoadAsync() - 从数据流中加载指定长度的数据到缓冲区
     *     ReadInt32(), ReadByte(), ReadString() 等 - 从缓冲区中读取数据
     * DataWriter - 将数据写入数据流,即写入 IOutputStream
     *     WriteInt32(), WriteByte(), WriteString() 等 - 将数据写入缓冲区
     *     StoreAsync() - 将缓冲区中的数据保存到数据流
     * 
     * StorageStreamTransaction - 用于写数据流到文件的类(具体用法,详见下面的代码)
     *     Stream - 数据流(只读)
     *     CommitAsync - 将数据流保存到文件
     *     
     * 注:WinRT 中的关于存储操作的相关类都在 Windows.Storage 命名空间内
     */
    
    using System;
    using Windows.Storage;
    using Windows.Storage.Streams;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    
    namespace XamlDemo.FileSystem
    {
        public sealed partial class ReadWriteStream : Page
        {
            public ReadWriteStream()
            {
                this.InitializeComponent();
            }

     private async void btnWrteStream_Click(object sender, RoutedEventArgs e)
            {
                //在指定的目录下创建指定的文件
                StorageFolder storageFolder = KnownFolders.PicturesLibrary;
                StorageFile storageFile = await storageFolder.CreateFileAsync("stream.txt", CreationCollisionOption.ReplaceExisting);

                string textContent = "i am stream";
                StorageStreamTransaction transaction = await storageFile.OpenTransactedWriteAsync();
                DataWriter dataWriter = new DataWriter(transaction.Stream);
                //将字符串写入数据流,然后将数据流保存到文件
                dataWriter.WriteString(textContent);
                transaction.Stream.Size = await dataWriter.StoreAsync();
                await transaction.CommitAsync();

                lblMsg.Text = "写入成功";
            }

            private async void btnReadStream_Click(object sender, RoutedEventArgs e)
            {
                //在指定的目录下获取指定的文件
                StorageFolder storageFolder = KnownFolders.PicturesLibrary;
                try
                {
                    StorageFile storageFile = await storageFolder.GetFileAsync("stream.txt");
                    if (storageFile != null)
                    {
                        IRandomAccessStream randomStream = await storageFile.OpenAsync(FileAccessMode.Read);
                        DataReader dataReader = new DataReader(randomStream);
                        ulong size = randomStream.Size;
                        if (size <= uint.MaxValue)
                        {
                            //获取数据流,从中读取字符串值并显示
                            uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
                            string fileContent = dataReader.ReadString(numBytesLoaded);

                            lblMsg.Text = "读取结果:" + fileContent;
                        }
                    }

                }
                catch(Exception ex)
                {
                    lblMsg.Text = "读取文件失败:" +ex;
                }
           

            }
        }
    }

    4、演示如何读写“最近访问列表”和“未来访问列表”

    <StackPanel Margin="0,50 ">

                <TextBlock Name="lblMsg" FontSize="14"></TextBlock>
                <Button Name="btnAddToMostRecentlyUseList" Content="AddToMostRecentlyUseList" Click="btnAddToMostRecentlyUseList_Click"  Margin="5"></Button>
                <Button Name="btnGetMostRecentlyUsedList" Content="GetMostRecentlyUsedList" Click="btnGetMostRecentlyUsedList_Click"  Margin="5"></Button>
                <Button Name="btnAddToFutureAccessLsit" Content="AddToFutureAccessList" Click="btnAddToFutureAccessLsit_Click" Margin="5"></Button>
                <Button Name="btnGetFutureAccessList" Content="GetFutureAccessList" Click="btnGetFutureAccessList_Click" Margin="5"></Button>
            </StackPanel>

    FileSystem/CacheAccess.xaml.cs

    /*
              * 演示如何读写“最近访问列表”和“未来访问列表”
              * 注:如果需要读写某扩展名的文件,需要在 Package.appxmanifest 增加“文件类型关联”声明,并做相应的配置
              *
              * StorageFolder - 文件夹操作类
              *     获取文件夹相关属性、重命名、Create...、Get...等
              *
              * StorageFile - 文件操作类
              *     获取文件相关属性、重命名、Create...、Get...、Copy...、Move...、Delete...、Open...、Replace...等
              *    
              * StorageApplicationPermissions - 文件/文件夹的访问列表
              *     MostRecentlyUsedList - 最近访问列表(实现了 IStorageItemAccessList 接口)
              *         Add(IStorageItem file, string metadata) - 添加文件或文件夹到“最近访问列表”,返回 token 值(一个字符串类型的标识),通过此值可以方便地检索到对应的文件或文件夹
              *             file - 需要添加到列表的文件或文件夹
              *             metadata - 自定义元数据,相当于上下文
              *         AddOrReplace(string token, IStorageItem file, string metadata) - 添加文件或文件夹到“最近访问列表”,如果已存在则替换
              *         GetFileAsync(string token) - 根据 token 值,在“最近访问列表”查找对应的文件
              *         GetFolderAsync(string token) - 根据 token 值,在“最近访问列表”查找对应的文件夹
              *         GetItemAsync(string token) - 根据 token 值,在“最近访问列表”查找对应的文件或文件夹
              *         Entries - 返回 AccessListEntryView 类型的数据,其是 AccessListEntry 类型数据的集合
              *     FutureAccessList - 未来访问列表(实现了 IStorageItemAccessList 接口)
              *         基本用法同“MostRecentlyUsedList”
              *        
              * AccessListEntry - 用于封装访问列表中的 StorageFile 或 StorageFolder 的 token 和元数据
              *     Token - token 值
              *     Metadata - 元数据
              *    
              * 注:WinRT 中的关于存储操作的相关类都在 Windows.Storage 命名空间内
              */

            protected async override void OnNavigatedTo(NavigationEventArgs e)
            {
                // 在指定的目录下创建指定的文件
                StorageFolder storageFolder = KnownFolders.PicturesLibrary;// KnownFolders.DocumentsLibrary;
                StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdCacheAccess.txt", CreationCollisionOption.ReplaceExisting);

                // 在指定的文件中写入指定的文本
                string textContent = "I am webabcd";
                await FileIO.WriteTextAsync(storageFile, textContent, Windows.Storage.Streams.UnicodeEncoding.Utf8);
            }


            private async void btnAddToMostRecentlyUseList_Click(object sender, RoutedEventArgs e)
            {
                // 获取文件对象
                StorageFolder storageFolder = KnownFolders.PicturesLibrary; // KnownFolders.DocumentsLibrary;
                StorageFile storageFile = await storageFolder.GetFileAsync("webabcdCacheAccess.txt");
                if(storageFile!=null)
                {
                    //将文件添加到“最近访问列表”,并获取对应的token值
                    string token = StorageApplicationPermissions.MostRecentlyUsedList.Add(storageFile, storageFile.Name);
                    lblMsg.Text = "token:"+token;
                }
            }

            private async void btnGetMostRecentlyUsedList_Click(object sender, RoutedEventArgs e)
            {
                AccessListEntryView entries = StorageApplicationPermissions.MostRecentlyUsedList.Entries;
                if(entries.Count>0)
                {
                    //通过token值,从 最近访问列表 中获取文件对象
                    AccessListEntry entry = entries[0];
                    StorageFile storageFile = await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(entry.Token);
                    string textContent = await FileIO.ReadTextAsync(storageFile);
                    lblMsg.Text = "MostRecentlyUsedList的第一个文件的文本内容:" + textContent;
                }
                else
                {
                    lblMsg.Text = "最近访问列表中无数据";
                }
            }

            private async void btnAddToFutureAccessLsit_Click(object sender, RoutedEventArgs e)
            {
                // 获取文件对象
                StorageFolder storageFolder = KnownFolders.PicturesLibrary;// KnownFolders.DocumentsLibrary;
                StorageFile storageFile = await storageFolder.GetFileAsync("webabcdCacheAccess.txt");

                if (storageFile != null)
                {
                    //将文件添加到“未来访问列表”,并获取对应的token值
                    string token = StorageApplicationPermissions.FutureAccessList.Add(storageFile, storageFile.Name);
                    lblMsg.Text = "token" + token;
                }
            }

            private async void btnGetFutureAccessList_Click(object sender, RoutedEventArgs e)
            {
                AccessListEntryView entries = StorageApplicationPermissions.FutureAccessList.Entries;
                if(entries.Count>0)
                {
                    //通过token值,从 未来访问列表中获取文件对象
                    AccessListEntry entry = entries[0];
                    StorageFile storageFile=await StorageApplicationPermissions.FutureAccessList.GetFileAsync(entry.Token);
                    string textContent = await FileIO.ReadTextAsync(storageFile);
                    lblMsg.Text = "FutureAccessList的第一个文件的文本内容:" + textContent;
                }
                else
                {
                    lblMsg.Text = "未来访问列表中无数据";
                }
            }
        }

  • 相关阅读:
    hdu1161 欧拉路
    ZOJ 3204 Connect them(字典序输出)
    [POJ1936]All in All
    [POJ1035]Spell checker
    [POJ2485]Highways
    [洛谷P3697]开心派对小火车
    【AIM Tech Round 5 (Div. 1 + Div. 2) 】
    What are the differences between an LES-SGS model and a RANS based turbulence model?
    How to permanently set $PATH on Linux/Unix?
    tar解压命令
  • 原文地址:https://www.cnblogs.com/ansen312/p/5920751.html
Copyright © 2011-2022 走看看