[英]How to get right path files in android
我的代码如下:
Scanner sc = null;
try {
sc = new Scanner(new File("assets/mainmenu/readSourceFile.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println(e1.toString());
e1.printStackTrace();
}
然后,logcat显示异常java.io.FileNotFoundException
我怎样才能找到我的档案? 我试过了
sc = new Scanner(new File("mainmenu/readSourceFile.txt"));
但是,它仍然抛出FilenotFoundException
我的文件位于文件夹assets / mainmenu / readSourceFile.txt中
我试试这个::
private InputStream is;
try {
is = this.getResources().getAssets().open("mainmenu/readSourceFile.txt");
} catch (IOException e) {
e.toString();
}
我使用getAssets来访问android中的资产文件。 但是,如果我使用InputStream
,我怎么能想读取文本文件
你试试这个......希望它能奏效
sc = new Scanner(new File("file:///android_asset/mainmenu/readSourceFile.txt");
编辑尝试这个
AssetFileDescriptor descriptor = getAssets().openFd("mainmenu/readSourceFile.txt");
FileReader reader = new FileReader(descriptor.getFileDescriptor());
从此处复制资产文件夹路径
您无法访问Android应用程序的assets
文件夹,就好像它们是文件系统上的常规文件一样(提示:它们不是)。 相反,您需要在活动/应用程序上下文中使用AssetManager
.Call getAssets()
来获取AssetManager
。
完成后,您可以使用open("mainmenu/readSourceFile.txt")
来获取InputStream
。
您现在可以像阅读其他任何内容一样阅读此InputStream
。 Apache Commons IO是一个很棒的库,用于处理输入和输出流。 根据您想要获取数据的方式,您可以尝试:
将整个文件读入String:
try { String contents = IOUtils.toString(in); } finally { IOUtils.closeQuietly(in); }
将整个文件读入一个字符串列表,每行一个:
try { List<String> lines = IOUtils.readLines(in); } finally { IOUtils.closeQuietly(in); }
一次遍历文件一行:
try { LineIterator it = IOUtils.lineIterator(in, "UTF-8"); while (it.hasNext()) { String line = it.nextLine(); // do something with line } } finally { IOUtils.closeQuietly(in); }
我遇到过同样的问题。 我注意到该文件不应包含层次结构。 如果将来有人遇到同样的问题,这对我有用。 `
InputStream is=null;
try {
is=activity.getAssets().open("fileInAssets.dat");
} catch (IOException e1) {
Log.e(TAG, "Erro while openning hosts file.");
e1.printStackTrace();
}
`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.