Java 加载文本文件
我目前正在尝试编写一个程序,可以从内部/外部存储中加载选定的文本文件,以便在Android应用程序中使用 我已尝试使用以下代码通过加载文件,但无效:Java 加载文本文件,java,android,Java,Android,我目前正在尝试编写一个程序,可以从内部/外部存储中加载选定的文本文件,以便在Android应用程序中使用 我已尝试使用以下代码通过加载文件,但无效: File sdcard = Environment.getExternalStorageDirectory(); File file = new File(sdcard,"file.txt"); 这要感谢 在后一种情况下,当用户选择文本文件时,它意外地返回false。对于第一个代码块,我也会遇到类似的错误。我了解到可以使用InputStream从
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"file.txt");
这要感谢
在后一种情况下,当用户选择文本文件时,它意外地返回false。对于第一个代码块,我也会遇到类似的错误。我了解到可以使用InputStream从uri加载文件,但我不知道如何实现这一点。感谢您的帮助。File File=new Filesdcard,File.txt
这并不意味着文件就在那里。你检查它,数据读起来就像
File sdcard = Environment.getDataDirectory();
File file = new File(sdcard,"file.txt");
if (file.exists()) {
InputStream readData;
byte[] buffer = new byte[4096];
int readLength;
try {
readData = new FileInputStream(file);
while ((readLength = readData.read(buffer)) > 0) {
// do work here to data
// readLength 4096 not always, last not as much often
}
readData.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
// do nothing file exist
}
必须已设置创建权限,否则将发生异常
多种数据读取方式您好,感谢您的回复。我试过你的代码,它说文件存在,但仍然显示文件无法读取。有什么建议吗?
File sdcard = Environment.getDataDirectory();
File file = new File(sdcard,"file.txt");
if (file.exists()) {
InputStream readData;
byte[] buffer = new byte[4096];
int readLength;
try {
readData = new FileInputStream(file);
while ((readLength = readData.read(buffer)) > 0) {
// do work here to data
// readLength 4096 not always, last not as much often
}
readData.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
// do nothing file exist
}