簡體   English   中英

從內部存儲讀取和寫入

[英]read and write from Internal storage

嘗試從文件讀取時出現此異常

java.io.FileNotFoundException:/data/data/.../files

我使用此方法是因為它可以在讀取文件時處理Unicode文本

public void save(String string )
{

String filename = "main";


FileOutputStream outputStream;

try {
  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
  outputStream.write(string.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}
}
public String read()
{
    try
    {

        Reader readerUnicode =
                new InputStreamReader(new FileInputStream(getFilesDir()), Charset.forName("UTF-16"));
                int e = 0;
                String f="";
                while ((e = readerUnicode.read()) != -1) {
                // cast to char. The casting removes the left most bit.
                 f = f+Character.toString((char) e);
                System.out.print(f);
                }

                return f;
    }
    catch(Exception e)
    {

        return e+"";
    }

}

如何獲取內部保存路徑

謝謝

您正在使用getFilesDir()但未設置實際的文件名。 只是目錄路徑。

嘗試在其中添加文件名。此外,您可能應該在保存和加載路徑中都添加.txt類的擴展名。

 new InputStreamReader(new FileInputStream(getFilesDir() + "/" + filename ), Charset.forName("UTF-16"));

並將filename更改為更明智的名稱。

String filename = "main.txt";

您可以/還應該在訪問文件之前檢查文件是否存在。 (盡管您還是嘗試捕獲)

File file = new File(getFilesDir() + "/" + filename);
if(!file.exists()) 
   return ""; 

暫無
暫無

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

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