我在尝试从文件
中读取时遇到此异常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+"";
}
}
如何检索内部保存路径
感谢
答案 0 :(得分:1)
您正在使用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 "";