簡體   English   中英

Windows環境中的文件路徑問題

[英]File path problems in windows environment

我有以下代碼行:

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

如果我在窗口中打印此行,則會得到錯誤的文件路徑:

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

在UNIX中,文件路徑正確無誤。

我知道我需要使其與Windows兼容,因此我嘗試使用FilenameUtils,但這不能解決問題。

在所有環境中,路徑均應正確。

使用File.getCanonicalFile()規范結果字符串。 它將轉換為正確的分隔符,也將刪除. 路徑段。

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());

當前的工作目錄. 取決於如何啟動應用程序。 你可能會用

System.getProperty("user.dir")

而不是獲得絕對路徑。

它可能會出現相同的問題:在Windows下單擊會出現問題。

解決方案/解決方法可能是在Windows下擁有一個批處理文件。

我傾向於在用戶的主文件夾中使用依賴於應用程序的目錄。 在前一個時期被隱藏時:

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

1)使用System.getProperty(“ file.separator”)獲得當前的OS文件分隔符。 2)新的java.io.File(“。”)。getAbsolutePath()將返回Linux中的Linux路徑(/ etc / uus /。)和Windows中的Windows路徑(例如:C:\\ xpto \\ sdfs。)

您需要根據需要進行標准化。

更換

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

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

更換

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM