Cách tạo tệp, ghi dữ liệu vào tệp và đọc dữ liệu từ tệp đó trên Android? Nếu có thể, hãy cung cấp đoạn mã.Cách tạo tệp trong Android?
Trả lời
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();}
tệp sẽ được ghi ở đâu? –
"/data/data/your_project_package_structure/files/samplefile.txt" – Petar
Bạn có cần gọi 'flush' trước 'close' không? –
tôi đã sử dụng đoạn mã sau để tạo ra một tập tin tạm thời để viết byte. Và nó hoạt động tốt.
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");
Tôi quyết định viết một lớp học từ chuỗi này có thể hữu ích cho người khác. Lưu ý rằng điều này hiện được dự định chỉ viết trong thư mục "tệp" (ví dụ: không ghi vào đường dẫn "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);
}
}
Tôi đã kiểm tra mã của bạn nhưng có một số lệnh không được chấp nhận cho API mới (17): Context.MODE_WORLD_READABLE và Context.MODE_WORLD_WRITEABLE cần được thay đổi. –
Ngoài các bit không được chấp nhận - bạn phải đóng cửa cuối cùng và bạn không cần tuôn ra trước khi đóng. Vui lòng không đăng mã sloppy –
Viết vào một tập tin 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();
}
đọc từ tập tin 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();
}
Lưu ý: đừng quên thêm hai phép này trong AndroidManifest. xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- 1. Ngày tạo tệp trong android
- 2. Tạo tệp jar trong Android
- 3. Cách tạo tệp pdf trên android
- 4. Android: Cách nhận ngày tạo tệp?
- 5. Xuất Android: cách tạo tệp .keystore?
- 6. Tạo tệp trong trình giả lập android
- 7. tạo tệp PDF từ android
- 8. Cách tạo TextArea trong Android
- 9. Cách tạo thư mục trong Android?
- 10. Tạo View-Object từ tệp XML trong android
- 11. Android: Tạo tệp bằng phương thức createNewFile()
- 12. Android tạo và viết xml thành tệp
- 13. Tạo các tệp tạm thời trong Android với NDK
- 14. Cách phát tệp GIF trong Android?
- 15. Cách mở tệp trong Android qua Intent
- 16. Cách đọc tệp csv trong android?
- 17. Cách tạo hộp thoại tải trong Android?
- 18. Cách tạo Thẻ cào trong Android?
- 19. Cách tạo nút hình ảnh trong Android?
- 20. Cách tạo nút Liên kết trong android
- 21. cách tạo kết nối Socket trong Android?
- 22. Android: làm cách nào để tạo đối tượng Tệp từ tệp nội dung?
- 23. Cách tạo tệp văn bản và chèn dữ liệu vào tệp đó trên Android
- 24. Cách tạo tệp hằng số trong Javascript?
- 25. Cách tạo Tệp bằng FILE_ATTRIBUTE_TEMPORARY trong C#?
- 26. Cách tạo tệp mới trong unix
- 27. Cách tạo tệp Jar trong Netbeans
- 28. Android - cách hủy đăng ký người nhận được tạo trong tệp kê khai?
- 29. Cách sử dụng tệp .key và .pem để tạo SSL socket trong Android?
- 30. Làm cách nào để tạo hoạt ảnh bằng các tệp xml trong android?
Nhìn vào [link] này (http://www.anddev.org/worki ng_with_files-t115.html) Nó chứa một hướng dẫn dễ làm theo về cách viết và đọc từ các tệp. – Prashast
http://developer.android.com/training/basics/data-storage/files.html –