簡體   English   中英

Android從類路徑加載文件導致崩潰

[英]Android load file from classpath causing crash

我正在嘗試在Android的靜態上下文中從類路徑加載文件,SO上的每個類似問題都建議使用MyClass.class.getClassLoader().getResourcesAsStream(<filepath>) ,但這會導致我的應用在崩潰之前崩潰打開。

我的目標SDK是19,最低SDK級別是17,並且我正在使用運行Android Lollipop的手機

這是我嘗試加載文件“ locations.xml”的代碼部分:

public static final String LOCATIONS_FILE_PATH = "locations.xml";

public static ArrayList<City> getLocations(String locations_file_path) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    Document document = null;
    try {
        builder = factory.newDocumentBuilder();
        document = builder.parse(
        City.class.getClassLoader().getResourceAsStream(locations_file_path));

該文件與引用它的java類位於同一包中。

logcat中給出的錯誤是DocumentBuilder.parse(...)IllegalArgumentException ,因為City.class.getClassLoader().getResourceAsStream("locations.xml"))返回null

我認為您需要驗證最終apk文件中的xml文件實際上是否包含在您認為的位置。

Android的更常見模式是將文件放在“ assets”目錄中,然后使用Activity的getAssets()方法從該目錄加載文件。

參閱以字符串形式讀取資產文件

作為getResourceAsStream的替代方法,您可以按照本教程中的說明使用FileInputStream

請注意 ,如果FileInputStream還返回null ,那么很有可能像@GreyBeardedGeek所說的那樣,實際上在最終apk文件中不包含xml文件。

相關代碼:

import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class DocumentBuilderDemo {

   public static void main(String[] args) {

      // create a new DocumentBuilderFactory
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

      try {
         // use the factory to create a documentbuilder
         DocumentBuilder builder = factory.newDocumentBuilder();

         // create a new document from input stream
         FileInputStream fis = new FileInputStream("Student.xml");
         Document doc = builder.parse(fis);

         // get the first element
         Element element = doc.getDocumentElement();

         // get all child nodes
         NodeList nodes = element.getChildNodes();

         // print the text content of each child
         for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println("" + nodes.item(i).getTextContent());
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

Student.xml(在您的情況下為locations.xml)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="10">
   <age>12</age>
   <name>Malik</name>
</student>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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