簡體   English   中英

FileWriter:如何設置目標文件夾?

[英]FileWriter: How to set the destination folder?

我當時正在開發一個小游戲(Android-App),我想將我的Highscores保存到一個.txt-File文件中,因為如果我將其保存在一個列表中,則每次啟動該應用程序時該列表都將為空新。 通常對於Java程序,這對我來說不是問題,因為FileWriter在程序文件夾中創建一個.txt。 如果我在Android中執行此操作,我會(當然)收到錯誤消息,表明他無法創建文件。

那么,如何告訴FileWriter在哪里保存文件以及應該在哪里保存呢? 如果文件名已經存在,例如FileOutput中的“ MODE_PRIVATE” -Mode,FileWriter會刪除現有文件並創建具有相同名稱的新文件嗎?

我知道我可以使用FileOutput / InputStream在內部存儲中保存文件,但是FileOutput只接受字節(.getBytes()-Method沒問題),但是我找不到將字節轉換回去的方法當我想閱讀它們時,將其轉換為字符串。

(對於任何語法錯誤,我深表歉意,因為英語不是我的母語)

更新:

首先,非常感謝到目前為止的幫助。 但是我仍然需要一些具體的幫助。 那就是我想要做的:每當我的游戲結束時,我都切換到“積分”活動並給他達到的積分。 在points-activity中,我將積分放入一個列表中,然后將此列表寫入內部存儲器中的文件中。 在Highscores-Activity中,我想讀取此文件並將文件的內容放入列表中,然后使用ListView在屏幕上打印出來。 這是編寫文件的代碼:

ArrayList<Integer> highscoreListe = new ArrayList<Integer>();
punkte = getIntent().getExtras().getInt("Punkte");
public void writeToExternalStoragePublic() throws IOException
 {
     String filename = "highscores.txt"; 

     FileOutputStream fos= null;
     OutputStreamWriter osw = null;
     fos= openFileOutput(filename,Context.MODE_PRIVATE);
     osw = new OutputStreamWriter(fos);
     for(Integer score : highscoreListe)
     {
         osw.write(score);
         osw.append(System.getProperty("line.separator"));
     }
     osw.close();
     fos.close();
 }

我在stackoverflow上閱讀了很多關於此的問題,但我仍然不知道如何讀取此文件,以便為文件中的每一行添加一個新字符串或int到列表中。 我希望你理解我想做什么。

請參考此鏈接以添加文件

http://developer.android.com/guide/topics/data/data-storage.html#pref

在仿真器模式下以“ APPEND模式”寫入文本文件,

does the FileWriter deletes an existing file and creates a new file with the same name if the filename already exists

是的,但考慮

public FileWriter(File file,
                  boolean append)
append - if true, then bytes will be written to the end of the file rather than the beginning 

您想使文件私有寫入內部存儲器。

暫無
暫無

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

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