开发者

Android File Not Found Exception

开发者 https://www.devze.com 2023-03-16 01:02 出处:网络
I am writing an android app and I am having a very frus开发者_JAVA技巧trating issue. I have some data stored in an XML file called \"ouritems.xml\" in a \"data\" folder.

I am writing an android app and I am having a very frus开发者_JAVA技巧trating issue. I have some data stored in an XML file called "ouritems.xml" in a "data" folder. I have this code that is supposed to read from this file.

 try {
            File fXmlFile = new File("data/ouritems.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
            nList = doc.getElementsByTagName("item");
        }
        catch(Exception e){
            e.printStackTrace();
        }

I have tried running this code in a plain java app, and it works perfectly. However, when I try to run the android app I get a "File not found exception". The file is stored in the app folder. And I CANNOT understand why it cannot be found. Is this some sort of android permission problem??


I have actually resolved this issue. I put the file in a res/raw folder. This is the only way I could actually save the file in a way Android could read form it. (The phone I am testing on, doesn't even have an SD card.). I then read it by calling getResources().openRawResource(R.raw.ouritems). Thank you for putting me on the right path! And I hope this can be helpful to someone else.


You will need to properly specify the full path to the file. Is the file on the SD card? In the apk raw asset folder? The File path you are using is a relative path that assumes a certain working directory which is not guaranteed to be what you think it is on Android.

You should specify an absolute path, not a relative one. What is the absolute path to the file on the Android system you are testing on?


you can't give absolute path to your src like C:\users.... your apk will be installed inside the sandbox area. /data/data is the path. if you have a package eg com.example.test then your path will be /data/data/com.example.test/ give your path as /data/data/ouritems.xml. if you have a package give accordingly.


If your xml file is in SD card you can use

File fXmlFile = new File(Environment.getExternalStorageDirectory()+"/ouritems.xml");

Thanks Deepak

0

精彩评论

暂无评论...
验证码 换一张
取 消