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
Works now after changing file.mkdirs(); to file.getParentFile().mkdirs();
Se explanation in the following Answer
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
Yes, using standard Java I/O.
Or maybe tell me why the example below fails miserably
Talented programmers know how to describe symptoms, rather than use pointless phrases like "fails miserably".
That being said, file.mkdirs();
creates a directory. You then try opening that directory as if it were a file, for the purposes of writing data to it. That does not work on any OS that I am aware of, and certainly not on Android. Please call mkdirs()
on something that will create the file's parent directory (e.g., file.getParentFile().mkdirs()
).
Also, never use concatenation to create a File
object. Use the proper File
constructor.
来源:https://stackoverflow.com/questions/9276745/is-it-possible-to-create-and-maintain-a-folder-structure-with-files-using-the-in