[英]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.