![](/img/trans.png)
[英]how to get the path of the image(.png) file that is stored in assets folder in android
[英]How to open a file in the assets folder using a path stored in the database?
我在数据库中存储了一个text1.txt
文件text1.txt
的路径,该文件包含我要显示的文本。 该文件位于资产文件夹asset / text1.txt中。
如何打开此文件并显示其内容?
代码是:
if (placetext != null) {
try
{
InputStream textpath = getAssets().open(text);
//Bitmap bit = BitmapFactory.decodeStream(textpath);
placetext.setText(text);
//placetext.setText(text);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
...而模拟器上的视图只是text1.txt,而不是文件的内容。
我已经有了解决方案
字符串text12 = b.getString(“ texts”)try {InputStream is = getAssets()。open(text12); // int size = is.available();
byte[] buffer = new byte[size]; is.read(buffer); is.close(); String text= new String(buffer); placetext = (TextView)findViewById(R.id.detailText2); placetext.setText(text); } catch (IOException e) { throw new RuntimeException(e); }
这很正常,因为:
InputStream textpath = getAssets().open(text);
我猜这里:文本代表您要打开的文件的名称。
placetext.setText(text);
这样会将传入的文本参数输入文本字段,因此现在是文件名。
要将文件的内容放入文本字段,您必须打开文件,读取文件并将内容存储在StringBuffer中,然后将StringBuffer内容放入文本字段中。
编辑:
StringBuilder text = new StringBuilder();
Scanner scanner = new Scanner(new FileInputStream(new File('yourfile')));
try {
while (scanner.hasNextLine()){
text.append(scanner.nextLine());
}
}
finally{
scanner.close();
}
}
在许多其他解决方案中,一种解决方案是用Java读取文件的内容。
希望能帮助到你
这就是我用来读取存储在/ assets文件夹中的XML内容的方法:
public static String getXMLFromAssets(Context ctx, String pathToXML){
InputStream rawInput;
//create a output stream to write the buffer into
ByteArrayOutputStream rawOutput = null;
try {
rawInput = ctx.getAssets().open(pathToXML);
//create a buffer that has the same size as the InputStream
byte[] buffer = new byte[rawInput.available()];
//read the text file as a stream, into the buffer
rawInput.read(buffer);
rawOutput = new ByteArrayOutputStream();
//write this buffer to the output stream
rawOutput.write(buffer);
//Close the Input and Output streams
rawOutput.close();
rawInput.close();
} catch (IOException e) {
Log.e("Error", e.toString());
}
//return the output stream as a String
return rawOutput.toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.