Jak utworzyć plik, zapisać w nim dane i odczytać z niego dane na urządzeniu z systemem Android? Jeśli to możliwe, podaj fragment kodu.Jak utworzyć plik na Androida?
Odpowiedz
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();}
gdzie plik zostanie zapisany? –
"/data/data/twoj_projekt_folderu_produktu/files/samplefile.txt" – Petar
Czy musisz wywołać 'flush' przed' close'? –
Użyłem następujący kod utworzyć plik tymczasowy do pisania bajtów. I działa dobrze.
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");
Postanowiłem napisać klasę z tego wątku, która może być pomocna dla innych. Zauważ, że jest to obecnie przeznaczone do zapisu tylko w katalogu "files" (np. Nie zapisuje do ścieżek "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;
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);
}
}
Mam sprawdzić kod, ale istnieją pewne polecenia, które są przestarzałe dla nowego interfejsu API (17): Context.MODE_WORLD_READABLE i Context.MODE_WORLD_WRITEABLE należy zmienić. –
Oprócz przestarzałych bitów - musisz zamknąć w końcu i nie musisz spłukiwać przed zamknięciem. Nie publikuj niechlujnego kodu –
Zapis do pliku 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();
}
Odczyt z pliku 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();
}
Uwaga: nie zapomnij dodać te dwa uprawnienia w AndroidManifest. xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- 1. Jak utworzyć reklamę pełnoekranową na Androida?
- 2. Pobierz plik programowo na Androida
- 3. Jak utworzyć plik chm?
- 4. Jak utworzyć plik .mbtiles?
- 5. Jak mogę utworzyć krawędzie na obrazie na Androida?
- 6. Jak utworzyć plik PDF za pomocą iText lub innej biblioteki na Androida?
- 7. Plik hosts gospodarza Androida
- 8. Utwórz plik w emulatorze androida
- 9. Jak utworzyć plik prokutów heroku?
- 10. Jak utworzyć fałszywy/"wirtualny" plik?
- 11. Jak mogę utworzyć DialogFragment z ListActivity na Androida?
- 12. Jak utworzyć wycieczkę z przewodnikiem dla aplikacji na Androida
- 13. jak utworzyć pływający wideo popup player na Androida?
- 14. Jak utworzyć nakładkę podczas udostępniania w aplikacji na Androida?
- 15. Jak utworzyć intent Androida, który przenosi dane?
- 16. Jak utworzyć widget Androida z opcjami?
- 17. Jak zaakceptować otrzymany plik bluetooth w aplikacji na Androida?
- 18. jak przesłać plik przy użyciu phonegapa na Androida?
- 19. Plik tekstowy dołączania Androida:
- 20. Jak wybrać folder na Androida?
- 21. Jak utworzyć plik aplikacji z Fastlane na symulatorze
- 22. Jak utworzyć plik lokalnie z szablonami ansibli na maszynie programistycznej
- 23. Jak programowo utworzyć całkowicie pusty plik rzadki na Linuksie?
- 24. Jak utworzyć plik wykonywalny ELF na Mac OS X?
- 25. Jak mogę utworzyć nowy plik applicationhost.config na serwerze IIS Express?
- 26. Qt utworzyć plik wykonywalny
- 27. jak utworzyć nowy plik java.io.file w pamięci?
- 28. Jak mogę utworzyć plik binarny w Perlu?
- 29. Jak utworzyć plik Excel z Nodejs?
- 30. Jak utworzyć duży plik PDF, pół szybko
Spójrz na to [link] (http://www.anddev.org/worki ng_with_files-t115.html) Zawiera łatwy do naśladowania samouczek dotyczący pisania i odczytu z plików. – Prashast
http://developer.android.com/training/basics/data-storage/files.html –