Saving txt files with Android Studio

Asked

Viewed 1,149 times

0

I am having trouble saving the name typed by the user in a txt file.

When I press save, it says it was created, but I can’t read.

Context fileContext;

public BancoDeDados(Context fileContext) {
    this.fileContext = fileContext;
}

public void gravar(String nome) {
    try {
        FileOutputStream os = fileContext.getApplicationContext().openFileOutput("bdNome.txt", Context.MODE_PRIVATE);
        os.write(nome.getBytes());
        os.close();
        System.out.println("Salvou");
    } catch (IOException e) {
        System.out.println("Deu erro");
    }
}
  • And where is your reading method? What have you tried to do?

  • The permits have come through?!

1 answer

1

Guys, here’s the answer. I got.

public void gravar ( String data ) {
        try {
            FileOutputStream fOut = fileContext.openFileOutput ( "arquivo.txt" , Context.MODE_PRIVATE ) ;
            OutputStreamWriter osw = new OutputStreamWriter ( fOut ) ;
            osw.write ( data ) ;
            osw.flush ( ) ;
            osw.close ( ) ;
            System.out.println("ok");
        } catch ( Exception e ) {
            e.printStackTrace ( ) ;
            System.out.println("Deu erro");
        }
    }

public String ler ( ) {
    StringBuffer datax = new StringBuffer("");
    try {
        FileInputStream fIn = fileContext.openFileInput ( "arquivo.txt" ) ;
        InputStreamReader isr = new InputStreamReader ( fIn ) ;
        BufferedReader buffreader = new BufferedReader ( isr ) ;

        String readString = buffreader.readLine ( ) ;
        while ( readString != null ) {
            datax.append(readString);
            readString = buffreader.readLine ( ) ;
        }

        isr.close ( ) ;
        System.out.println("ok");
    } catch ( IOException ioe ) {
        System.out.println("Deu erro");
        ioe.printStackTrace ( ) ;
    }
    return datax.toString() ;
}

Browser other questions tagged

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