简体   繁体   English

从内部存储读取和写入

[英]read and write from Internal storage

I am having this exception when trying to read from the file 尝试从文件读取时出现此异常

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

I used this method because it can handle Unicode text while reading from the file 我使用此方法是因为它可以在读取文件时处理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+"";
    }

}

how can I retrieve the internal save path 如何获取内部保存路径

thanks 谢谢

You are using getFilesDir() But not setting the actual file name. 您正在使用getFilesDir()但未设置实际的文件名。 Just the directory path. 只是目录路径。

Try adding the file name in. Plus, you should probably add an extension like .txt to both the save and load path. 尝试在其中添加文件名。此外,您可能应该在保存和加载路径中都添加.txt类的扩展名。

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

and change filename to something more sensible. 并将filename更改为更明智的名称。

String filename = "main.txt";

You could/should also check the file exists before accessing it. 您可以/还应该在访问文件之前检查文件是否存在。 (Although you do try catch anyway) (尽管您还是尝试捕获)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM