我有一个字符串文本,我必须将其保存在一个新的或已创建的文件夹中,并使用我自己的文件扩展名。用户还应该能够复制和使用这些文件。我已经浏览了很多教程,但大多数教程都令人困惑。libgdx(android平台)中有没有简单的方法来将字符串保存为具有我自己的扩展名的文件,并从内存中的文件列表中将其取回。 我需要的是:
- 将文件保存到新文件夹或现有文件夹的函数(可供用户使用)。提供字符串作为参数。
- 另一个获取指定文件夹中“.my”文件列表的函数。
最佳答案
保存:
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)
{
}
}
}
关于java - Libgdx:在android中保存和取回文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25324768/