How to create a txt file?

Asked

Viewed 10,348 times

4

In Java I use the PrintWriter and works perfectly, but on Android I’m getting a lot, it doesn’t work at all.

Can someone help me with this? It’s a simple thing, but I’m stuck. I needed to create a .txt simple with a string. Thank you in advance!

  • ...in a directory you can visit later with a file manager to be able to view the file, correct?

  • yes, just create a txt on the desktop or in my documents for example.

1 answer

9

First you must enter the permission to write to sdcard in Androidmanifest.xml before the application tag :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

After creating the attributes, you will create the directory:

private File diretorio;
private String nomeDiretorio;
private String diretorioApp;

After that, you should set the directory:

diretorioApp = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            + "/"+nomeDiretorio+"/";

diretorio = new File(diretorioApp);
diretorio.mkdirs();

After you create the directory where the file will be saved, you can create the txt file:

//Quando o File() tem um parâmetro ele cria um diretório.
//Quando tem dois ele cria um arquivo no diretório onde é informado.
File fileExt = new File(diretorioApp, nomeArquivo);

//Cria o arquivo
fileExt.getParentFile().mkdirs();

//Abre o arquivo
FileOutputStream fosExt = null;
fosExt = new FileOutputStream(fileExt);

//Escreve no arquivo
fosExt.write(etTexto.getText().toString().getBytes());

//Obrigatoriamente você precisa fechar
fosExt.close();

Any doubt, give a touch ;D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.