java - 带空格的文件路径

标签 java

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

最佳答案

指定 Windows 文件路径时,必须转义“\”字符,否则指定的路径将不是您所期望的。指定路径的正确方法是:

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

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

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

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

关于java - 带空格的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24784610/

相关文章:

java - 为什么使用 CachingParanamer 时 Paranamer 不返回方法名称?

Java 后台缓冲区和动画

Java 媒体框架 : extract audio info from mp3 file

java - Android - 强制横向显示纵向 View

java - 如何在Java中将字符串行插入到字符串数组中

java - 将字节数组加载到 p :graphicImages

java - ArrayList 子列表的索引越界

java - 可以在 JTextArea 上显示图片吗?

java - 使用 'javah' 使用 JNI 生成头文件

java.lang.IndexOutOfBoundsException : using try, 捕获