0
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,这是怎么回事?

4

1 回答 1

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

按照这种方式将数据写入要存储在 sdcard 上的文件中。告诉我这是否对你有帮助

于 2013-06-26T18:11:55.363 回答