[英]Java NIO file path issue
我使用以下代碼來獲取路徑
Path errorFilePath = FileSystems.getDefault().getPath(errorFile);
當我嘗試使用File NIO移動文件時,我收到以下錯誤:
java.nio.file.InvalidPathException: Illegal char <:> at index 2: \C:\Sample\sample.txt
我也嘗試使用URL.encode(errorFile)
導致相同的錯誤。
路徑\\C:\\Sample\\sample.txt
必須沒有前導\\
。 它應該只是C:\\Sample\\sample.txt
您需要將找到的資源轉換為URI 。 它適用於所有平台,可以保護您免受路徑可能出現的錯誤。 您不必擔心完整路徑的樣子,無論是以'\\'還是其他符號開頭。 如果你考慮這些細節 - 你做錯了什么。
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
String platformIndependentPath = Paths.get(classloader.getResource(errorFile).toURI()).toString();
為了使它適用於Windows和Linux \\ OS X,請考慮這樣做:
String osAppropriatePath = System.getProperty( "os.name" ).contains( "indow" ) ? filePath.substring(1) : filePath;
如果你想擔心性能我System.getProperty( "os.name" ).contains( "indow" )
為常量
private static final boolean IS_WINDOWS = System.getProperty( "os.name" ).contains( "indow" );
然后使用:
String osAppropriatePath = IS_WINDOWS ? filePath.substring(1) : filePath;
為了確保在任何驅動器號上的Windows或Linux上獲得正確的路徑,您可以執行以下操作:
path = path.replaceFirst("^/(.:/)", "$1");
這樣說:如果字符串的開頭是斜杠,那么一個字符,然后一個冒號和另一個斜杠,用字符,冒號和斜線替換它(保留前導斜杠)。
如果您使用的是Linux,則不應該在路徑中使用冒號,並且不會匹配。 如果你在Windows上,這適用於任何驅動器號。
擺脫前導分隔符的另一種方法是創建一個新文件並將其轉換為字符串,然后:
new File(Platform.getInstallLocation().getURL().getFile()).toString()
嘗試使用像這樣的C:\\\\Sample\\\\sample.txt
注意雙反斜杠。 因為反斜杠是Java String轉義字符,所以必須鍵入其中兩個以表示單個“實際”反斜杠。
要么
Java允許在任何平台上使用任何類型的斜杠,並適當地進行轉換。 這意味着您可以輸入。 C:/Sample/sample.txt
它會在Windows上找到相同的文件。 但是,我們仍然將路徑的“根”作為問題。
處理多個平台上的文件最簡單的解決方案是始終使用相對路徑名。 Sample/sample.txt
等文件名
免責聲明:我沒有在正常的Windows環境中測試過這個問題。
"\\\\C:\\\\"
需要是"C:\\\\"
final Path errorFilePath = Paths.get(FileSystems.getDefault().getPath(errorFile).toString().replace("\\C:\\","C:\\"));
我的Windows框有一個類Linux環境,所以我不得不將"/C:/"
更改為"C:\\\\"
。
此代碼經過測試,可在類似Linux的Windows環境中運行:
final Path errorFilePath = Paths.get(FileSystems.getDefault().getPath(errorFile).toString().replace("/C:/","C:\\"));
根據您將如何使用Path對象,您可以完全避免使用Path:
// works with normal files but on a deployed JAR gives "java.nio.file.InvalidPathException: Illegal char <:> "
URL urlIcon = MyGui.class.getResource("myIcon.png");
Path pathIcon = new File(urlIcon.getPath()).toPath();
byte bytesIcon[] = Files.readAllBytes(pathIcon);
// works with normal files and with files inside JAR:
InputStream in = MyGui.class.getClassLoader().getResourceAsStream("myIcon.png");
byte bytesIcon[] = new byte[5000];
in.read(bytesIcon);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.