如何使用 java 访问名称中包含 space 字符的文件?

How to access file that have space character in it's name in using java?

我无法访问名称中包含空格的文件。

我的代码:

String fileName = "This is my file.txt";
String path = "/home/myUsername/folder/";
String filePath = path + filename;
f = new BufferedInputStream(new FileInputStream(filePath));

我得到 FileNotFoundException

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class AccessMyFile {
    public static void main(String[] args) throws IOException {
        File file = new File("/home/This is my file.txt");
        System.out.println(file.exists());//true
        System.out.println(file.isFile());//true
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        while(bis.available()>0) {
            System.out.print((char)bis.read());
        }
    }//main
}//class

File: /home/This is my file.txt

输出:

hello world

使用java.io.File检查是否存在。然后你知道你的代码是否有效。

首先,参数文件名中有一个拼写错误:

String **fileName** = "This is my file.txt";
    String filePath = path + **filename**;

这是您的示例的更新代码:

  String fileName = "This is my file.txt";
            String path = File.separator + "home" + File.separator + "myUsername" + File.separator + "folder" + File.separator;
            String filePath = path + fileName;
            BufferedInputStream f = new BufferedInputStream(new FileInputStream(filePath));

I am able to read the file with spaces in file name.

Using File.separator we let the code to replace the file separator based on OS.