//Writing a file... try{// catches IOException belowfinalString TESTSTRING =newString("Hello Android");/* We have to use the openFileOutput()-method
* the ActivityContext provides, to
* protect your file from others and
* This is done for security-reasons.
* We chose MODE_WORLD_READABLE, because
* we have nothing to hide in our file */FileOutputStream fOut = openFileOutput("samplefile.txt",
MODE_PRIVATE);OutputStreamWriter osw =newOutputStreamWriter(fOut);// Write the string to the file
osw.write(TESTSTRING);/* ensure that everything is
* really written out and close */
osw.flush();
osw.close();//Reading the file back.../* We have to use the openFileInput()-method
* the ActivityContext provides.
* Again for security reasons with
* openFileInput(...) */FileInputStream fIn = openFileInput("samplefile.txt");InputStreamReader isr =newInputStreamReader(fIn);/* Prepare a char-Array that will
* hold the chars we read back in. */char[] inputBuffer =newchar[TESTSTRING.length()];// Fill the Buffer with data from the file
isr.read(inputBuffer);// Transform the chars to a StringString readString =newString(inputBuffer);// Check if we read back the same chars that we had written outboolean isTheSame = TESTSTRING.equals(readString);Log.i("File Reading stuff","success = "+ isTheSame);}catch(IOException ioe){ioe.printStackTrace();}
Decidi escrever uma classe a partir deste tópico que pode ser útil para outras pessoas. Observe que atualmente isso se destina a gravar apenas no diretório "arquivos" (por exemplo, não grava nos caminhos "sdcard").
import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import android.content.Context;publicclassAndroidFileFunctions{publicstaticString getFileValue(String fileName,Context context){try{StringBuffer outStringBuf =newStringBuffer();String inputLine ="";/*
* We have to use the openFileInput()-method the ActivityContext
* provides. Again for security reasons with openFileInput(...)
*/FileInputStream fIn = context.openFileInput(fileName);InputStreamReader isr =newInputStreamReader(fIn);BufferedReader inBuff =newBufferedReader(isr);while((inputLine = inBuff.readLine())!=null){
outStringBuf.append(inputLine);
outStringBuf.append("\n");}
inBuff.close();return outStringBuf.toString();}catch(IOException e){returnnull;}}publicstaticboolean appendFileValue(String fileName,Stringvalue,Context context){return writeToFile(fileName,value, context,Context.MODE_APPEND);}publicstaticboolean setFileValue(String fileName,Stringvalue,Context context){return writeToFile(fileName,value, context,Context.MODE_WORLD_READABLE);}publicstaticboolean writeToFile(String fileName,Stringvalue,Context context,int writeOrAppendMode){// just make sure it's one of the modes we supportif(writeOrAppendMode !=Context.MODE_WORLD_READABLE
&& writeOrAppendMode !=Context.MODE_WORLD_WRITEABLE
&& writeOrAppendMode !=Context.MODE_APPEND){returnfalse;}try{/*
* We have to use the openFileOutput()-method the ActivityContext
* provides, to protect your file from others and This is done for
* security-reasons. We chose MODE_WORLD_READABLE, because we have
* nothing to hide in our file
*/FileOutputStream fOut = context.openFileOutput(fileName,
writeOrAppendMode);OutputStreamWriter osw =newOutputStreamWriter(fOut);// Write the string to the file
osw.write(value);// save and close
osw.flush();
osw.close();}catch(IOException e){returnfalse;}returntrue;}publicstaticvoid deleteFile(String fileName,Context context){
context.deleteFile(fileName);}}
Eu verifiquei seu código, mas existem alguns comandos que foram descontinuados para a nova API (17): Context.MODE_WORLD_READABLE e Context.MODE_WORLD_WRITEABLE precisam ser alterados.
Victor Gil
4
Além dos bits descontinuados - você deve fechar finalmente e não precisa descarregar antes de fechar. Por favor, não poste código
incorreto
4
Escreva em um arquivo test.txt:
String filepath ="/mnt/sdcard/test.txt";FileOutputStream fos =null;try{
fos =newFileOutputStream(filepath);byte[] buffer ="This will be writtent in test.txt".getBytes();
fos.write(buffer,0, buffer.length);
fos.close();}catch(FileNotFoundException e){
e.printStackTrace();}catch(IOException e){
e.printStackTrace();}finally{if(fos !=null)
fos.close();}
Respostas:
A partir daqui: http://www.anddev.org/working_with_files-t115.html
fonte
flush
antesclose
?flush
é redundante. De acordo com os documentos, a chamadaclose
será realizada pelaflush
primeira vez. docs.oracle.com/javase/6/docs/api/java/io/…Eu usei o código a seguir para criar um arquivo temporário para escrever bytes. E está funcionando bem.
fonte
Decidi escrever uma classe a partir deste tópico que pode ser útil para outras pessoas. Observe que atualmente isso se destina a gravar apenas no diretório "arquivos" (por exemplo, não grava nos caminhos "sdcard").
fonte
Escreva em um arquivo test.txt:
Leia do arquivo test.txt:
Nota: não esqueça de adicionar essas duas permissões no AndroidManifest.xml
fonte