//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();}
Decidí escribir una clase de este hilo que podría ser útil para otros. Tenga en cuenta que actualmente está destinado a escribir solo en el directorio "archivos" (por ejemplo, no escribe en rutas "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);}}
Revisé su código pero hay algunos comandos que están en desuso para la nueva API (17): Context.MODE_WORLD_READABLE y Context.MODE_WORLD_WRITEABLE necesita ser cambiado.
Victor Gil
44
Además de los bits en desuso, debe cerrar finalmente y no necesita lavar antes de cerrar. No publique código descuidado
Mr_and_Mrs_D el
4
Escriba en un archivo 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();}
Respuestas:
Desde aquí: http://www.anddev.org/working_with_files-t115.html
fuente
flush
antesclose
?flush
es redundante. Según los documentos, las llamadasclose
se realizaránflush
primero. docs.oracle.com/javase/6/docs/api/java/io/…Usé el siguiente código para crear un archivo temporal para escribir bytes. Y está funcionando bien.
fuente
Decidí escribir una clase de este hilo que podría ser útil para otros. Tenga en cuenta que actualmente está destinado a escribir solo en el directorio "archivos" (por ejemplo, no escribe en rutas "sdcard").
fuente
Escriba en un archivo test.txt:
Leer del archivo test.txt:
Nota: no olvide agregar estos dos permisos en AndroidManifest.xml
fuente