Eclipse on macOS 檔案路徑為 C:\ ?

Jason
Jason
Sep 7, 2018 · 3 min read

這兩天在 Mac 上用 Eclipse 處理 Java Web Application 有關圖片讀取的 Servlet 時,遇到一個很奇妙的現象,就是我在建立 File 物件時,路徑錯用了 C:\ ,但 Application 執行儲存和讀取檔案都正常,而我卻在 Finder 裡面怎麼樣也找不到這個實體檔案。

TL;DR

/Applications/Eclipse.app/Contents/MacOS

Finder 找不到檔案?

當然把 File 要使用的路徑改為 / 開頭,檔案就會在 Macintosh HD/Volumes下找到了,但是我還是很好奇這到底是什麼一回事。

踩到問題

由於公司做的產品都是以 Windows 系統為主,因此很定義都是用 Windows 的結構為主,包含路徑的預設值也是 C:\,當然這類的設定都會開放給使用者自己修改,我過去都用 Windows,所以沒特別注意去調整這個設定,因此這次忘了因應 macOS 做修改。

檔案到底在哪裡?

就算 File 的 path 是給定 C:\MyFolder 在 macOS 上是不合理的,但系統還是運作正常,代表的我 Mac 裡面肯定有這個檔案,但是我卻怎麼都找不到,就算用了號稱是 macOS 上最強的免費搜尋 EasyFind ,也還是看不倒個影子。

藏在 Eclipse 裡面?

後來在這篇文章中,終於找到方法,可以透過以下程式,驗出目前檔案的路徑。

File testFile = new File("");
String currentPath = testFile.getAbsolutePath();
System.out.println("current path is: " + currentPath);

而得出來的路徑如下

/Applications/Eclipse.app/Contents/MacOS

沒錯,就是藏在 Eclipse 的應用程式底下,如果用搜尋工具搜尋時, App 下的目錄是會被忽略的,這也是為什麼我找不到檔案的原因。

因此要先用 Finder 進入該 App 結構,再開始搜尋該 ,就可以找到了。最終就看到自訂的目錄出現在上面的路徑底下

C/\MyFolder

對,資料夾名稱就是這樣,這也延伸了令一個議題,也就是 slash 應該要使用 Java 提供的 static variable => File.separator ,自動判斷要用 slash 或 backward slash 來建立 path ,才能有效運用 Java 跨平台的優勢,也才不會在非 Windows 的系統上,建立出這種看似奇怪的目錄。

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade