简体   繁体   中英

File path problems in windows environment

I have the following line of code:

"%s/ramp_adapter/user_%d/ramp_file_receipt/%d".format(new java.io.File(".").getAbsolutePath().replace("/.",""), endpointId, fileId)

If I print this line in window I get wrong file path:

E:\git\project\codeAdapters\rampAdapter\./ramp_adapter/user_1001/ramp_file_receipt/3

In unix, the file path is coming correct.

I know that I need to make it compatible with windows and so I tried using FilenameUtils but this didn't resolved the problem.

The path should be correct in all the environments.

Use File.getCanonicalFile() to norm the resulting string. It converts to the right separator and also removes . path segments.

String s = "E:\\git\\project\\codeAdapters\\rampAdapter\\./ramp_adapter/user_1001/ramp_file_receipt/3";
File f = new File(s).getCanonicalFile();
assertEquals("E:\\git\\project\\codeAdapters\\rampAdapter\\ramp_adapter\\user_1001\\ramp_file_receipt\\3", f.toString());

The current working directory . depends on how ie where the application was started. You might use

System.getProperty("user.dir")

instead of getting the absolute path.

It probably will exhibit the same problem: clicking under Windows will be problematic.

The solution/workaround might be to have a batch file under Windows.

I tend to use an application dependent directory in the user's home folder. When hidden with a preceding period:

File myAppDir = new File(System.getProperty("user.home") + "/.myappname";
myAppDir.mkdir();

1) Use System.getProperty("file.separator") to obtain the current OS file separator. 2) new java.io.File(".").getAbsolutePath() will return linux paths (/etc/uus/.)in Linux and Windows paths in windows (ex: C:\\xpto\\sdfs.)

You need to standardize as you wish.

Replace

"%s/ramp_adapter/user_%d/ramp_file_receipt/%d"

with

"%s" + File.separatorChar + "ramp_adapter" + File.separatorChar + "user_%d" + File.separatorChar + "ramp_file_receipt" + File.separatorChar + "%d"

Replace

getAbsolutePath().replace("/.","")

with

getAbsolutePath().replace(File.separator + ".", "")

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