2014-07-16 103 views
1
String filepath = E:\TestCode\My Demo File\abc.xml 

我想用这个文件路径创建文件,这个文件路径有空格。带空格的文件路径

FileInputStream file = new FileInputStream(new File(filePath)); 
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = builderFactory.newDocumentBuilder(); 
Document xmlDocument = builder.parse(file); 

它抛出FileNotFoundException

+1

请参阅http://docs.oracle.com/javase/tutorial/java/data/characters.html。您需要在字符串中使用“\\”而不是“\”。 – DavidPostill

+0

你知道这四行中的哪一行会抛出异常吗? –

+1

'String filepath = E:\ TestCode \ My Demo File \ abc.xml' will not compile .. –

回答

1

指定Windows文件路径时,必须转义'\'字符,否则指定的路径将不会完全符合您的预期。指定路径的正确方法应该是:

String filepath = "E:\\TestCode\\My Demo File\\abc.xml"; 

或者,您可以使用正斜杠作为路径分隔符,则File类会自动将其转换为正确的分离器为您的平台:

String filepath = "E:/TestCode/My Demo File/abc.xml"; 

我已经添加了缺少您在原始问题中提供的代码中缺少的引号和分号。

+0

或者只是使用'/ '因为'文件'足够聪明,可以计算出正确的分隔符... –

+0

@Boris真的,我已经更新了我的答案,谢谢你的通知;) – Laf