private void writeResults() {
// TODO Auto-generated method stub
String TAG = Screen3.class.getName();
File file = new File(getFilesDir(), "history.txt");
try {
file.createNewFile();
FileWriter filewriter = new FileWriter(file, true);
BufferedWriter out = new BufferedWriter(filewriter);
out.write(workout + " - " + averageSpeed + " - " + totalDistance
+ " - " + timerText + " - " + amountDonated + "\n ");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, e.toString());
}
}
我有这个代码在锻炼之后将用户的统计信息写入名为history.txt的.txt文件,但运行此文件没有错误。但是当我在手机上浏览Android/data/packagename/
时,没有history.txt,为什么会这样?
答案 0 :(得分:0)
您没有正确调用外部存储目录
public class externalwriter{
private static File mFile = null;
public static String getFileName() {
if (mFile.exists()) {
return mFile.getAbsolutePath();
} else {
return "";
}
}
/**
* Creates the history file on the storage card.
*/
private static void createFile() {
// Check if external storage is present.
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
// Create a folder History on storage card.
final File path = new File(Environment.getExternalStorageDirectory() +
"/History");
if (!path.exists()) {
path.mkdir();
}
if (path.exists()) {
// create a file HISTORYFILE.
mFile = new File(path, "HISTORYFILE.txt");
if (mFile.exists()) {
mFile.delete();
}
try {
mFile.createNewFile();
} catch (IOException e) {
mFile = null;
}
}
}
}
/**
* Write data to the history file.
* @param messages to be written to the history file.
*/
public static void writeHistory(final String log) {
if ((mFile == null) || (!mFile.exists())) {
createFile();
}
if (mFile != null && mFile.exists()) {
try {
final PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(mFile, true)));
out.println(log);
out.close();
} catch (IOException e) {
Log.w("ExternalStorage", "Error writing " + mFile, e);
}
}
}
/**
* Deletes the history file.
* @return true if file deleted, false otherwise.
*/
public static boolean deleteFile() {
return mFile.delete();
}
}
按照这种方式将数据写入要存储在SD卡上的文件中。告诉我这是否有助于你