Home > Back-end >  Android throws java.io.FileNotFoundException when trying to parse path to documentBuilder
Android throws java.io.FileNotFoundException when trying to parse path to documentBuilder

Time:10-03

So im trying to read an xml file with google map's marker options and parse it into an array in Android Studio:

try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

        Uri path = Uri.fromFile(new File("src/main/assets/local_markers.xml"));
        
        Document document = documentBuilder.parse(path.toString());

        //parsing

    } catch (ParserConfigurationException ex) {
        ex.printStackTrace(System.out);
    } catch (SAXException ex) {
        ex.printStackTrace(System.out);
    } catch (IOException ex) {
        ex.printStackTrace(System.out);
    };

It throws java.io.FileNotFoundException: /src/main/assets/local_markers.xml (No such file or directory) and array just gets filled with empty strings.

I tried so many diferent methods of parsing a file into a documentBuilder but nothing changes. File path is 100% correct since i copied it with Android studio "copy path" option.

CodePudding user response:

Try using AssetManager :

AssetManager manager = getAssets();
InputStream stream;

try {

    stream = manager.open("local_markers.xml");
    Document document = parser.getDocument(stream);
} catch (ParserConfigurationException ex) {
    ex.printStackTrace(System.out);
} catch (SAXException ex) {
    ex.printStackTrace(System.out);
} catch (IOException ex) {
    ex.printStackTrace(System.out);
};
  • Related