2017-02-22 142 views
0

我想解析SVG文件以獲取在android應用程序中使用Xpath的路徑。本機java以下面的方式解析路徑。如何設置FileInputStream的文件路徑?

try { 
    Document document = builder.parse(
      new FileInputStream("c:\\employees.xml")); 
} catch (SAXException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

我嘗試使用如下所示的FileDescriptor

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = null; 
     try { 
      builder = factory.newDocumentBuilder(); 
     } catch (ParserConfigurationException e) { 
      e.printStackTrace(); 
     } 


     AssetManager assetManager = getBaseContext().getAssets(); 
     AssetFileDescriptor assetFileDescriptor = null; 
     try { 
      assetFileDescriptor = assetManager.openFd("android.svg"); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     FileDescriptor fileDescriptor = assetFileDescriptor.getFileDescriptor(); 
     FileInputStream stream = new FileInputStream(fileDescriptor); 

     try { 
      Document document = builder.parse(stream); 
     } catch (SAXException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

但是我的應用程序停止工作。我的代碼有什麼問題?

+1

我認爲答案已經在stackoverflow。 這可能會幫助你[鏈接](http://stackoverflow.com/questions/14553292/fileinputstream-doesnt-work-with-the-relative-path) – vm345

回答

0

你不需要FileDescriptor。嘗試如下。

InputStream input = assetManager.open("android.svg"); //From your asset folder 

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = null; 
try { 
    builder = factory.newDocumentBuilder(); 
} catch (ParserConfigurationException e) { 
    e.printStackTrace(); 
} 

和解析您的inputbuilder

Document document = builder.parse(input);