简体   繁体   中英

java File.separator becomes “%” in path of the File on Windows

I try to read files from the resources folder. The problem is, that the File.separator turns into a " %" on Windows.

String inputFilesFolder = "input_files" + File.separator;
File file = new File(classLoader.getResource(inputFilesFolder + "filename").getFile());

The inputFilesFolder is still fine ( input_files/ ), but after creating the file file.getPath() becomes D:\\blabla\\input_files%filename .

Then I try to read the file, but I get a FileNotFoundException (big surprise). What's wrong here?

File.separator is a file system thing. When you're using classLoader.getResource() always use forward slash as the name of a resource is a '/'-separated path name.

See Javadoc for getResource()

尝试这个:

File file = new File(classLoader.getResource(inputFilesFolder + filename).toURI());

How about

 String inputFilesFolder = "input_files" + File.separator;
 File file = new File(classLoader.getResource(inputFilesFolder + filename).toString());

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