使用Java读取路径中带有空格的文件 [英] Read file with whitespace in its path using Java

查看:820
本文介绍了使用Java读取路径中带有空格的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用FileInputStream打开名称中包含空格的文件.

I am trying to open files with FileInputStream that have whitespaces in their names.

例如:

String fileName = "This is my file.txt";
String path = "/home/myUsername/folder/";

String filePath = path + filename;
f = new BufferedInputStream(new FileInputStream(filePath));

结果是抛出FileNotFoundException. 我试图将filePath硬编码为"/home/myUserName/folder/This\\ is\\ my\\ file.txt"只是为了看看我是否应该转义空格字符,并且它似乎没有用. 关于这个问题有什么建议吗?

The result is that a FileNotFoundException is being thrown. I tried to hardcode the filePath to "/home/myUserName/folder/This\\ is\\ my\\ file.txt" just to see if i should escape whitespace characters and it did not seem to work. Any suggestions on this matter?

只是与所有人都在同一个页面上,每个人都在查看此问题...打开名称中没有空格的文件是可行的,但包含空格的文件将失败.权限既不是这里的问题,也不不是文件夹分隔符.

Just to be on the same page with everyone viewing this question...opening a file without whitespace in its name works, one that has whitespaces fails. Permissions are not the issue here nor the folder separator.

推荐答案

带空格的文件名可以正常工作

File name with space works just fine

这是我的代码

File f = new File("/Windows/F/Programming/Projects/NetBeans/TestApplications/database prop.properties");
        System.out.println(f.exists());
        try
        {
            FileInputStream stream = new FileInputStream(f);
        }
        catch (FileNotFoundException ex)
        {
            System.out.println(ex.getMessage());
        }

f.exists()始终返回true毫无问题

这篇关于使用Java读取路径中带有空格的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆