Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the filename as string if the file is under the assets directory?

  • I have xml file under ASSETS dir (com.android.project\assets\xml\file.xml).
  • I want to call a (following) function to read the xml file and return the contents as String.
  • The function requires the path of the file as string. I don't know how to give the path of the file as string.

    private String getXML(String path){
    
      String xmlString = null;
    
      AssetManager am = this.getAssets();
      try {
        InputStream is = am.open(path);
        int length = is.available();
        byte[] data = new byte[length];
        is.read(data);
        xmlString = new String(data);
      } catch (IOException e1) {
          e1.printStackTrace();
      }
    
      return xmlString;
    }
    

The file.xml:

    <Items>
        <ItemData>
            <ItemNumber>ABC</ItemNumber>
            <Description>Desc1</Description>        
            <Price>9.95</Price>        
            <Weight>10.00</Weight>    
        </ItemData>    
        <ItemData>        
            <ItemNumber>XYZ</ItemNumber>        
            <Description>"Desc2"</Description>        
            <Price>19.95</Price>
            <Weight>22.22</Weight>
        </ItemData>
    </Items>

QUESTIONS:

  • How can I call the function getXML(String path) with a path as string parameter, if my file is located under \assets\xml\file.xml ?

  • Finally, Is there any better way of reading XML file as a String?

Thank you!

like image 718
wafers Avatar asked Dec 06 '25 01:12

wafers


2 Answers

The following would work:

InputStream is = context.getAssets().open("xml/file.xml");
like image 183
Anu Avatar answered Dec 08 '25 13:12

Anu


the path is just the path under the assets directory using forward slash (/)

so assets/x/y.z is referenced as this.getAssets().open("x/y.z");

That isnt the correct way to read the data - Inputstream.read isnt garunteed to read all the data it returns the number of bytes read - likely this will work for smaller file but you might get problems with bigger ones.

This is general code i read to to read text files, instead of a FileReader use an InputStreamReader

StringBuilder sw = new StringBuilder();
BufferedReader reader = new BufferedReader( new FileReader(file));
String readline = "";
while ((readline = reader.readLine()) != null) { 
    sw.append(readline);
}
String string = sw.toString();
like image 43
siliconeagle Avatar answered Dec 08 '25 13:12

siliconeagle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!