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;
}