簡體   English   中英

如何使用數據庫中存儲的路徑打開資產文件夾中的文件?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM