【发布时间】:2021-12-30 19:54:11
【问题描述】:
我正在尝试访问 android 中的文本文件,但它给出了错误 open failed: ENOENT (No such file or directory),因为文本文件存在于手机中。
if (txt_file.endsWith(".txt")) {
try {
Log.e("TAG", "path " + txt_file);
InputStream is = new FileInputStream(txt_file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
byte[] dataToSave = Base64.encode(bytes, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
我在InputStream 之前记录了txt_file,它正在返回文本文件的正确路径。
【问题讨论】:
-
尝试使用Scanner代替InputStream来读取文件
-
您能否详细说明一下,因为
is.read(b)中存在错误,因为没有使用 Scanner 的读取方法。 -
Log.e("TAG", "path " + txt_file);请告诉我们使用的路径。 -
你应该添加:
if ( !new File(txt_file).exists() return; -
您还应该添加:
if ( !new File(txt_file).canRead() return;
标签: java android io text-files