Libgdx:在android中保存并获取文件

时间:2014-08-15 10:16:13

标签: java android libgdx

我有一个文本作为字符串,我必须将它保存在一个新的或已经创建的文件夹中,并使用我自己的文件名扩展名。用户也应该能够复制和使用这些文件。我已经浏览了很多教程,但最重要的是令人困惑。在 libgdx android 平台)中有任何简单的方法使用我自己的扩展名将字符串保存为文件,并将其从内存中的文件列表中恢复。 我需要的是:

  1. 将文件保存到新文件夹或已存在文件夹的功能(可供用户使用)。将String作为参数。
  2. 获取" .my"的列表的另一个功能指定文件夹中的文件。

1 个答案:

答案 0 :(得分:1)

保存:

    public boolean saveToFile(String fileName)
    {
        FileHandle fileHandle = Gdx.files.local(fileName + ".txt");
        BufferedWriter bw = new BufferedWriter(fileHandle.writer(false));
        try
        {
            bw.append("stuff");

        }
        catch (IOException e)
        {
            e.printStackTrace();
            return false;
        }
        finally
        {
            try
            {
                bw.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return true;
    }

并阅读:

        FileHandle f = Gdx.files.local(fileName + ".txt");
        BufferedReader r = null;
        try
        {
            r = new BufferedReader(f.reader());
            String line = null;
            while((line = r.readLine()) != null)
            {
                //read the lines
            }
        }
        catch (GdxRuntimeException e)
        {
            //file does not exist yet
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (r != null)
            {
                try
                {
                    r.close();
                }
                catch (IOException e)
                {
                }
            }
        }