JAVA Android,使用GetResourceAstream访问文件
我想在我的android应用程序中处理属性文件。属性文件位于主文件夹中,与其他jar文件一起位于该文件夹中。我知道,那不是最好的 代码: 因此,第2行的日志显示: libcore.net.url.JarURLConnectionImpl$JarURLConnectionInputStream@421302e8 在这种形式下,logcat调用System.err:JAVA Android,使用GetResourceAstream访问文件,java,android,inputstream,Java,Android,Inputstream,我想在我的android应用程序中处理属性文件。属性文件位于主文件夹中,与其他jar文件一起位于该文件夹中。我知道,那不是最好的 代码: 因此,第2行的日志显示: libcore.net.url.JarURLConnectionImpl$JarURLConnectionInputStream@421302e8 在这种形式下,logcat调用System.err: java.io.FileNotFoundException/libcore.net.url.JarURLConnectionImpl$
java.io.FileNotFoundException/libcore.net.url.JarURLConnectionImpl$JarURLConnectionInputStream@42097218: open failed: ENOENT (No such file or directory)
但当我这样评论时:
InputStream propStream=MainActivity.class.getResourceAsStream("data.properties");
Log.d("propStreamOutput",propStream.toString());
File data = new File(propStream.toString());
// Reader reader;
// try {
// reader = new FileReader(data);
// dataProp = new Properties();
// dataProp.load( reader );
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
那就没有系统了!当然,第2行的日志调用也是如此。如果您真的想使用getResourceAsStream(),那么您必须将该文件与.java文件一起放在“src”文件夹中 这通常是标准Java应用程序的方式,但在Android上,执行此类操作的最常用方式是将文件放在“资产”文件夹中,via,可从您的或任何其他用户访问该文件夹。如下图所示:
InputStream is = null;
try {
is = context.getAssets().open("data.properties");
} catch (final IOException e) {
e.printStackTrace();
} finally {
closeStreamGracefully(is);
}
GetResourceAsStream返回一个InputStream。当您在此上调用toString时,它将返回一个。然后,当您创建数据文件并尝试读取它时,将尝试打开一个类似@sdqzeffdfsf的文件。如果您不想从该文件中读取属性,请使用
这是针对标准java的。然而,在android系统中,您通常使用您认为
propStream.toString()
做什么?(提示:快速调试会告诉您)
InputStream is = null;
try {
is = context.getAssets().open("data.properties");
} catch (final IOException e) {
e.printStackTrace();
} finally {
closeStreamGracefully(is);
}
Properties properties = new Properties();
properties.load(propStream);