在android中从手机读取文本文件



我试图访问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,它正在返回文本文件的正确路径。

试试这个

fun readFile(file: File?): String {
var fileContent: String = ""
try {
val scan = Scanner(file)
while (scan.hasNextLine()) {
fileContent = scan.nextLine()
}
scan.close()
} catch (e: IOException) {
e.printStackTrace()
fileContent = ""
}
return fileContent
}

最新更新