gpt4 book ai didi

android - 是否可以使用内部存储创建和维护包含文件的文件夹结构

转载 作者:太空狗 更新时间:2023-10-29 16:23:13 28 4
gpt4 key购买 nike

I have studied the link below, but it doesn't answer my question. http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

If the answer to the question in the title is yes. Could someone please supply a simple example creating a subfolder and adding a file to that folder? And perhaps show how to read the file back from the sub folder?

Or maybe tell me why the example below fails miserably

在将 file.mkdirs(); 更改为 file.getParentFile().mkdirs();
后现在可以使用在下面的答案中解释

public static void Test(String path, String fileName, String fileStr, Context ctx)
{

SaveFile(path, fileName, fileStr, ctx);
String returnFileStr = ReadFile(path, fileName, ctx);
}
public static Boolean pathExists(String path, Context ctx)
{
Boolean result = false;
String[] pathSeqments = path.split("/");
String pathStr = "";
for(int i = 0;i<pathSeqments.length;i++ )
{
pathStr += pathSeqments[i];
if(!new File(ctx.getFilesDir() +"/" + pathStr).exists())
{
result = false;
break;
}
pathStr += "/";
result = true;
}
return result;
}

public static void SaveFile(String path, String fileName, String fileStr, Context ctx) {
try {
File file = new File(ctx.getFilesDir() +"/" + path, fileName); //new File(ctx.getFilesDir() +"/" + path + "/" + fileName);
file.getParentFile().mkdirs();

FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);

osw.write(fileStr);

osw.flush();
osw.close();

} catch (IOException ioe) {
ioe.printStackTrace();
}
}

public static String ReadFile(String path, String fileName, Context ctx) {
String fileStr = null;
try {
if(pathExists(path, ctx))
{
File file = new File(ctx.getFilesDir() +"/" + path, fileName);
FileInputStream fIn = new FileInputStream(file);

StringWriter writer = new StringWriter();

IOUtils.copy(fIn, writer, "UTF-8");
fileStr = writer.toString();
}

} catch (IOException ioe) {
ioe.printStackTrace();
}
return fileStr;
}

最佳答案

Is it possible to create and maintain a folder structure with files Using the Internal Storage

是的,使用标准的 Java I/O。

Or maybe tell me why the example below fails miserably

有才华的程序员知道如何描述症状,而不是使用“惨败”等毫无意义的短语。

也就是说,file.mkdirs(); 创建了一个目录。然后您尝试打开该目录,就好像它是一个文件一样,以便向其中写入数据。这不适用于我所知道的任何操作系统,当然也不适用于 Android。请调用 mkdirs() 来创建文件的父目录(例如,file.getParentFile().mkdirs())。

此外,切勿使用串联来创建 File 对象。使用正确的 File 构造函数。

关于android - 是否可以使用内部存储创建和维护包含文件的文件夹结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9276745/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com