Skip to content Skip to sidebar Skip to footer

How To Create Nested Folders And File In Context.mode_private?

I have a requirement where files and folders are required to be written in nested structure using Context.MODE_PRIVATE. I found that we can create file using openFileOutput(FILENAM

Solution 1:

You need to create foo directory first then create file inside that dir.

Use getDir(String name, int mode) to create directory into internal memory. The method Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory.


For example

// Create directory into internal memory;Filemydir= context.getDir("mydir", Context.MODE_PRIVATE);
// Get a file myfile within the dir mydir.FilefileWithinMyDir=newFile(mydir, "myfile"); 
// Use the stream as usual to write into the file.FileOutputStreamout=newFileOutputStream(fileWithinMyDir); 

So your need to write your code as

// Create foo directory into internal memory;Filemydir= getDir("foo", Context.MODE_PRIVATE);
// Get a file myText.txt within the dir foo.FilefileWithinMyDir=newFile(mydir, "myText.txt"); 
// Use the stream as usual to write into the file.try {
    FileOutputStreamout=newFileOutputStream(fileWithinMyDir);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

to create foo/myText.txt into internal storage.


For nested directories, you should use normal java method. Like

new File(parentDir, "childDir").mkdir();

So updated example should be

// Create directory into internal memory;Filemydir= getDir("mydir", Context.MODE_PRIVATE);

// Create sub-directory mysubdirFilemySubDir=newFile(mydir, "mysubdir");
mySubDir.mkdir();

// Get a file myfile within the dir mySubDir.FilefileWithinMyDir=newFile(mySubDir, "myfile"); 
// Use the stream as usual to write into the file.FileOutputStreamout=newFileOutputStream(fileWithinMyDir);

Solution 2:

public OutputStream openFile(String absolutePath)throws FileNotFoundException {
  Filefile=newFile(absolutePath);
  newFile(file.getParent()).mkdirs();

  returnnewFileOutputStream(absolutePath);
}

public OutputStream openInternalFile(String relativePath)throws FileNotFoundException {
  StringrootPath=this.getFilesDir().getPath();
  Filefile=newFile(rootPath, relativePath);
  return openFile(file.getAbsolutePath());
}

This is what I came up which covers your use case. You can either pass the absolutePath or relativePath. behind the scene it does create a nested folders inside internal storage and returns back an OutputStream which you can start write into it.

Post a Comment for "How To Create Nested Folders And File In Context.mode_private?"