Android 如何使用数据库中存储的路径打开资产文件夹中的文件?
我的数据库中存储了一个指向文件Android 如何使用数据库中存储的路径打开资产文件夹中的文件?,android,sqlite,text,Android,Sqlite,Text,我的数据库中存储了一个指向文件text1.txt的路径,该文件包含我要显示的文本。该文件位于assets文件夹assets/text1.txt中 如何打开此文件并显示其内容 代码是: if (placetext != null) { try { InputStream textpath = getAssets().open(text); //Bitmap bit = BitmapFactory.decodeStream(textpath);
text1.txt
的路径,该文件包含我要显示的文本。该文件位于assets文件夹assets/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();
}
}
…并且emulator上的视图只是text1.txt,而不是文件的内容
我已经有了解决方案
String text12=b.getString(“文本”)
试一试{
InputStream=getAssets().open(text12)//
int size=is.available()
这很正常,因为:
InputStream textpath = getAssets().open(text);
我猜这里:文本表示要打开的文件的名称
placetext.setText(text);
这会将传入参数的文本放入textfield中,因此现在输入文件名
要将文件内容放入textfield,必须打开文件,读取并将内容存储在StringBuffer中,然后将StringBuffer内容放入textfield
编辑:
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();
}
感谢您的回复;InputStream textpath=getAssets()。打开(文本),text表示sqlite上的字段,其中包含路径。它可以处理图像文件和图像路径,但不能处理文本。txtOk你能更准确地解释一下这个问题吗。据我所知,你想获取存储在应用程序的资产文件夹中的文件内容,并在文本字段中显示它的内容吗?对吗?看看这个:我可以图片引用了这个链接,它很有效。所以,我尝试使用文本,但它不起作用。。
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();
}