我正在尝试从 Android 项目内的本地存储读取文件。 但是我仍然遇到类似文件未找到异常的错误。我已经打印了文件的路径,并且我已经使用浏览器检查了文件是否位于同一路径上。但我仍然有异常(exception)。
try {
File file = new File("D:\\Android SDK\\AndroidWorkspace\\Assignment4Test\\app\\src\\main\\assets\\studentnameid.txt");
if (file.exists()) {
System.out.println("File Is there ");
} else {
//It always executes the else blog.
file.createNewFile();
System.out.println(" file is not there so its creating Created File");
}
System.out.println(file.getAbsolutePath());
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
非常感谢您的帮助。
谢谢, 克里希纳
最佳答案
D:\\Android SDK\\AndroidWorkspace\\Assignment4Test\\app\\src\\main\\assets\\studentnameid.txt
是 Windows PC 上文件的路径。安卓不是Windows。您不使用 Windows 文件系统路径来引用 Android 上的任何内容。
根据该路径,我的猜测是您的项目中的 assets/
中有一个文件。如果是这样,请使用 AssetManager
(通过 Context
上的 getAssets()
)及其 open()
方法来访问你的 Assets 。这将为您提供一个可直接或通过 InputStreamReader
读取的 InputStream
。
关于java - 即使文件存在于机器中,也无法使用 Android 访问本地机器上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56960356/