简体   繁体   中英

How do you reference a file in a path that has a space in it in Java?

I'm working on a project that involves reading a txt file, and the way I currently have it set up is with...

reader = new BufferedReader(new FileReader(new File(url)));

...where url is a String. I don't have it set up for the user to input their own file path (or my ultimate goal to be able to choose it in a window, but that's a different matter), so I Just have url set to something like...

"file:///C:/Users/Jeremiah/Desktop/generic_text_file.txt"

My problem is that, with this technique, I can't include spaces in the file path or I'll get an invalid character exception, yet most of files and directories on a computer that a person actually deals with has spaces in it, even ones that come on the computer like "My Documents".

I've also tried passing the String through a method to escape the spaces by adding "\\" in front of them, but that still isn't working.

public String escapeSpaces(String string){
    int cursor = 0;
    System.out.println(string);
    while(cursor<string.length()){
        if(string.charAt(cursor)==' '){
            string = string.substring(0,cursor)+"\\"+string.substring(cursor, string.length());
            System.out.println(string);
            cursor++;
        }
        cursor++;
    }
    return string;
}

So how would one get around this issue so that I could instead reference a file in say...

"file:///C:/Users/Jeremiah/Desktop/S O M A N Y S P A C E S/generic_text_file.txt"

Any feedback is appreciated.

You can't construct a File with a URl string. Just pass a proper filename string directly to the constructor of File, or indeed the constructor of FileReader. There is no issue with spaces in the filename.

it still doesn't allow me to use a file path with spaces

Yes it does. You are mistaken.

escaped or not

Filenames do not require escaping. URLS require escaping. But you're just making an unnecessary mess by using the URL class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM