Arquivo texto - gravar e ler |
Top Previous Next |
|
package com.arquivo;
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream;
import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.Toast;
public class ArquivoActivity extends Activity {
final String ARQUIVO = "arquivo.txt";
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
gravarArquivoTexto(); lerArquivoTexto(); // excluirArquivo(); }
// GRAVAR UM ARQUIVO TEXTO public void gravarArquivoTexto() { try { FileOutputStream out = openFileOutput(ARQUIVO, MODE_APPEND); String texto = "Este texto será gravado"; out.write(texto.getBytes()); out.close(); } catch (Exception e) { Log.e("ERRO", e.getMessage()); } }
// LER UM ARQUIVO TEXTO public void lerArquivoTexto() { try { File f = getFileStreamPath(ARQUIVO); Log.i("MSG", "Lendo arquivo " + f.getAbsolutePath()); if (f.exists()) { FileInputStream in = openFileInput(ARQUIVO); int tamanho = in.available(); byte bytes[] = new byte[tamanho]; in.read(bytes); String s = new String(bytes); Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); in.close(); } } catch (Exception e) { Log.e("ERRO", e.getMessage()); } }
// EXCLUIR UM ARQUIVO TEXTO public void excluirArquivo() { deleteFile(ARQUIVO); Log.i("MSG", "arquivo excluido"); } } |