Yahor Urbanovich
Yahor Urbanovich

Reputation: 773

How to create File in specfic folder in code?

I create file in onPause(). How to create this file in folder "documents" inside my app? I found some information about File.mkdir(). This code must to create folder, at least as stated in developer.android.com

 @Override
 protected void onPause() {
    super.onPause();

    textFromEditText = createText.getText().toString();
    FileOutputStream fos = null;
    OutputStreamWriter os = null;

    try {
        fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
        os = new OutputStreamWriter(fos, "UTF-8");
        os.write(textFromEditText);

    } catch (IOException e) {
        Toast.makeText(this, errorWriting, Toast.LENGTH_SHORT).show();
    } finally {
        Closeable cls = (os != null ? os : fos);

        if (cls != null) {
            try {
                cls.close();
            } catch (IOException e) {
                Toast.makeText(this, errorSaving, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Upvotes: 0

Views: 59

Answers (2)

Josef Korbel
Josef Korbel

Reputation: 1208

You need to declare your path for the file to be saved in. For example:

File path = context.getFilesDir();

then user it while saving with combinating path + filename.

Also you're saving the file as PRIVATE, that means you can have trouble spotting it by yourself in the directory.

Upvotes: 0

Zahan Safallwa
Zahan Safallwa

Reputation: 3914

You can use below code to create a directory and later create a file inside it. You can also write something to the file like below.

public void createFile(String myfile, String body){ //myfile is filename, body is the text to be written in our file
try
{
    File root = new File(Environment.getExternalStorageDirectory(), "documents"); 
    if (!root.exists()) {
        root.mkdirs(); //creating directory documents
    }
    File newfile = new File(root, myfile); //creating file in documents folder
    FileWriter writer = new FileWriter(newfile);
    writer.append(body);
    writer.flush();
    writer.close();

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

}
} 

Upvotes: 1

Related Questions