Wie erstelle ich eine Datei, schreibe Daten hinein und lese Daten davon auf Android? Wenn möglich, ein Code-Snippet bereitstellen.Wie erstelle ich eine Datei in Android?
Antwort
From here: http://www.anddev.org/working_with_files-t115.html
//Writing a file...
try {
// catches IOException below
final String TESTSTRING = new String("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 = new OutputStreamWriter(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 = new InputStreamReader(fIn);
/* Prepare a char-Array that will
* hold the chars we read back in. */
char[] inputBuffer = new char[TESTSTRING.length()];
// Fill the Buffer with data from the file
isr.read(inputBuffer);
// Transform the chars to a String
String readString = new String(inputBuffer);
// Check if we read back the same chars that we had written out
boolean isTheSame = TESTSTRING.equals(readString);
Log.i("File Reading stuff", "success = " + isTheSame);
} catch (IOException ioe)
{ioe.printStackTrace();}
wo wird die Datei geschrieben? –
"/data/data/your_project_package_structure/files/samplefile.txt" – Petar
Müssen Sie 'flush' vor' close' aufrufen? –
habe ich den folgenden Code eine temporäre Datei für das Schreiben von Bytes zu erstellen. Und es funktioniert gut.
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write(data1);
fo.close();
System.out.println("file created: "+file);
url = upload.upload(file);
}
//deleting the file
file.delete();
System.out.println("file deleted");
Ich entschied mich, eine Klasse aus diesem Thread zu schreiben, die für andere hilfreich sein kann. Beachten Sie, dass derzeit nur im Verzeichnis "files" geschrieben werden soll (z. B. nicht in Pfade "sdcard" schreiben).
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;
public class AndroidFileFunctions {
public static String getFileValue(String fileName, Context context) {
try {
StringBuffer outStringBuf = new StringBuffer();
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 = new InputStreamReader(fIn);
BufferedReader inBuff = new BufferedReader(isr);
while ((inputLine = inBuff.readLine()) != null) {
outStringBuf.append(inputLine);
outStringBuf.append("\n");
}
inBuff.close();
return outStringBuf.toString();
} catch (IOException e) {
return null;
}
}
public static boolean appendFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context, Context.MODE_APPEND);
}
public static boolean setFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context,
Context.MODE_WORLD_READABLE);
}
public static boolean writeToFile(String fileName, String value,
Context context, int writeOrAppendMode) {
// just make sure it's one of the modes we support
if (writeOrAppendMode != Context.MODE_WORLD_READABLE
&& writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
&& writeOrAppendMode != Context.MODE_APPEND) {
return false;
}
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 = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(value);
// save and close
osw.flush();
osw.close();
} catch (IOException e) {
return false;
}
return true;
}
public static void deleteFile(String fileName, Context context) {
context.deleteFile(fileName);
}
}
Ich habe Ihren Code überprüft, aber es gibt einige Befehle, die für die neue API (17) veraltet sind: Context.MODE_WORLD_READABLE und Context.MODE_WORLD_WRITEABLE müssen geändert werden. –
Abgesehen von den veralteten Bits - Sie müssen schließlich schließen und Sie müssen nicht vor dem Schließen flush. Bitte poste keinen schlampigen Code –
schreiben in eine Datei test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(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();
}
Lesen aus der Datei test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
int length = (int) new File(filepath).length();
byte[] buffer = new byte[length];
fis.read(buffer, 0, length);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fis != null)
fis.close();
}
Hinweis: vergessen Sie nicht, diese beiden Erlaubnis in AndroidManifest hinzuzufügen. xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- 1. Wie erstelle ich eine Datenbank in Android?
- 2. Wie erstelle ich eine Baumansicht in Android?
- 3. Erstelle eine AAR-Datei in Android Studio
- 4. Wie erstelle ich eine JAR-Datei von Android Studio
- 5. Wie erstelle ich eine TIFF-Datei?
- 6. Wie erstelle ich eine .pyd Datei?
- 7. Wie erstelle ich eine virtuelle Datei?
- 8. Wie erstelle ich eine .po Datei?
- 9. Wie erstelle ich eine CHM-Datei?
- 10. Wie erstelle ich eine gefälschte/"virtuelle" Datei?
- 11. Wie erstelle ich eine benutzerdefinierte Android-Bibliothek in Android Studio?
- 12. Wie kombiniere ich Bilder und erstelle eine mp4-Datei?
- 13. Wie erstelle ich eine Registerkarte in einem Tab in Android?
- 14. Wie erstelle ich ein AttributSet in Android?
- 15. Wie erstelle ich eine Batch-Datei mit einer Batch-Datei?
- 16. Wie erstelle ich eine MD5-Prüfsumme für eine Datei in Android?
- 17. Wie erstelle ich Hilfe-Schaltflächen in Android?
- 18. Wie erstelle ich eine PDF-Datei in einer UWP-App?
- 19. Wie erstelle ich eine .SQL-Datei in Ubuntu Server?
- 20. Wie erstelle ich eine neue Datei in Qt
- 21. Wie erstelle ich eine Datei in Java (kein Ordner)?
- 22. Wie erstelle ich eine tar.gz Datei in R?
- 23. Wie erstelle ich eine .p12-Datei in Ruby?
- 24. Wie erstelle ich eine JSON-Antwort in einer PHP-Datei?
- 25. Realbasic: Wie erstelle ich eine Datei in einem bestimmten Ordner?
- 26. Wie erstelle ich eine iPA-Datei in Xcode?
- 27. Wie erstelle ich eine CSX-Datei in Visual Studio?
- 28. Wie erstelle ich eine Hauptimportdatei in ES6?
- 29. Wie erstelle ich eine eigene Listener-Schnittstelle in Android?
- 30. Wie erstelle ich eine Sperre (concurrent.locks.Lock) in Android?
Schauen Sie sich diese [link] (http://www.anddev.org/worki ng_with_files-t115.html) Es enthält eine leicht verständliche Anleitung zum Schreiben und Lesen von Dateien. – Prashast
http://developer.android.com/training/basics/data-storage/files.html –