如何在 Android 中创建文件?
Posted
技术标签:
【中文标题】如何在 Android 中创建文件?【英文标题】:How to create a file in Android? 【发布时间】:2010-11-17 08:44:00 【问题描述】:如何在 android 上创建文件、向其中写入数据并从中读取数据?如果可能,请提供代码 sn-p。
【问题讨论】:
看看这个link 它包含一个关于如何读写文件的简单教程。 developer.android.com/training/basics/data-storage/files.html 【参考方案1】: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();
【讨论】:
文件会写到哪里? "/data/data/your_project_package_structure/files/samplefile.txt" 在close
之前需要打电话给flush
吗?
不,flush
是多余的。根据文档,调用close
将首先执行flush
。 docs.oracle.com/javase/6/docs/api/java/io/…
MODE_WORLD_READABL deprecated 这是我尝试使用它时得到的结果【参考方案2】:
我使用以下代码创建了一个用于写入字节的临时文件。而且它工作正常。
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);
//deleting the file
file.delete();
System.out.println("file deleted");
【讨论】:
【参考方案3】:写入文件 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();
从文件 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();
注意:不要忘记在AndroidManifest.xml中添加这两个权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
【讨论】:
【参考方案4】:我决定从这个线程编写一个可能对其他人有帮助的课程。请注意,这目前仅用于写入“files”目录(例如,不写入“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);
【讨论】:
我已经检查了您的代码,但有些命令已被新 API (17) 弃用:需要更改 Context.MODE_WORLD_READABLE 和 Context.MODE_WORLD_WRITEABLE。 除了不推荐使用的位 - 您必须最终关闭,并且您不需要在关闭之前刷新。请不要发布草率的代码以上是关于如何在 Android 中创建文件?的主要内容,如果未能解决你的问题,请参考以下文章
如何以编程方式在 android 中创建 *** 配置文件并连接到它?
我们如何在Android中重用已经在IOS中创建的Sqlite文件[重复]