Android中,文件存储方案也比较简单,一般使用 FileOutputStream/BufferedWriter写入文件,使用FileInputStream/BufferedReader读出文件内容。不过,文件是存放在/data/data/com.xxx.test/files/文件夹下面。
下面,我们看看示例代码,
// Write contents to the file
String data = "Hello World!";
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("testFile.txt", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Read the contents from the file
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("testFile.txt");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
content.append(line);
}
}catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(this, content.toString(), Toast.LENGTH_SHORT).show();
上述方式的文件,只可以供自身程序使用,如果其他程序想访问,则没有权限。下面,我们介绍一种可以让多个程序一起访问文件的方式,
Log.e(TAG, copyContent.toString());
try {
File fs = new File(Environment.getExternalStorageDirectory()+"/msc/" + fileName);
FileOutputStream outputStream =new FileOutputStream(fs);
outputStream.write(copyContent.getBytes());
outputStream.flush();
outputStream.close();
Toast.makeText(getBaseContext(), "File created successfully", Toast.LENGTH_LONG).show();
Log.e(TAG, "Successful");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
下面是读外部文件的代码范例,
mConfigPath = getExternalFilesDirs("test")[0].getAbsolutePath() + File.separator + "config.txt";
public Map<String, String> getSingleParameters(String mConfigPath) {
Map<String, String> mParametersList = new LinkedHashMap();
String mKey = "";
String mValue = "";
try {
FileReader mFileReader = new FileReader(mConfigPath);
BufferedReader mReader = new BufferedReader(mFileReader);
String mReadLine;
while((mReadLine = mReader.readLine()) != null) {
if (!mReadLine.startsWith("#") && mReadLine.trim().length() > 0) {
String[] mKeyValuePair = mReadLine.split("=");
mKey = mKeyValuePair[0].trim();
mValue = mKeyValuePair[1].trim();
mParametersList.put(mKey, mValue);
}
}
mReader.close();
mFileReader.close();
} catch (FileNotFoundException var9) {
var9.printStackTrace();
} catch (IOException var10) {
var10.printStackTrace();
}
return mParametersList;
}