簡體   English   中英

Android文件不寫

[英]Android File not writing

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了,怎么了?

您沒有正確調用外部存儲目錄

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上的文件中。 告訴我這是否對您有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM