2013-02-07 45 views
2

我有這樣的代碼試圖創建和我的JSON文件寫的,但我怎麼能做到這一點隱藏在任何操作系統(Windows或Mac)如何使用Java

File file = new File(System.getProperty("user.home") + File.separator + "Documents" + File.separator + "targetappConfig.json"); 

if (!(file.exists())) { 

    org.json.simple.JSONArray userDetails = new org.json.simple.JSONArray(); 
    userDetails.add(userDetail); 
    jsonObj.put("users", userDetails); 
    FileWriter fileWriter = new FileWriter(file); 
    fileWriter.write(jsonObj.toString()); 
    fileWriter.flush(); 
    fileWriter.close(); 
} 
+0

你對_hidden_​​的定義是什麼? – OscarRyz

+0

你不能。 (因爲不是所有的操作系​​統都支持隱藏的文件(謝天謝地!)) – Ingo

+1

你可以通過爲每個操作系統家族創建一個合適的方法來實現這一點。沒有標準的「隱藏」文件通用概念。此外,更好的方法來做你似乎試圖做的事情是將你的私人文件保存在一個私人文件夾中,用於這類事情。 (Windows上適當的'AppData'目錄,OS X上的〜/ Library/Application Support/Your App Name /'和Linux上的'〜/ .config/yourappname /')。 – millimoose

回答

2

我所做的是創建一個OSValidator,併爲每個操作系統編碼我的文件並將其保存在應用程序目錄(Windows:appdata,mac:Application Suport)中。這似乎是最容易做到的。

public class OSValidator { 
    private static String OS = System.getProperty("os.name").toLowerCase(); 

    public static boolean isWindows(){ 
     return (OS.indexOf("win")>=0); 
    } 

    public static boolean isMac(){ 
     return (OS.indexOf("mac")>=0); 
    } 

    public static boolean isUnix() { 
     return (OS.indexOf("nix") >=0 || OS.indexOf("nux") >=0 || OS.indexOf("aix") >= 0); 
    } 

    public static boolean isSolaris(){ 
     return (OS.indexOf("sunos") >=0); 
    } 
} 



if (OSValidator.isWindows()) { 
      System.out.println("This is Windows"); 
      file = new File(System.getenv("APPDATA") + File.separator + "TargetApp" + File.separator +"config.json"); 

      if (!file.exists()) { 
       try { 
        FileUtils.forceMkdir(file.getParentFile()); 
       } catch (IOException ex) { 
        Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex); 
       } 
      } 

     } else if (OSValidator.isMac()) { 
      System.out.println("This is Mac"); 

      file = new File(System.getProperty("user.home") + File.separator + "Library" + File.separator + "Application Support" 
        + File.separator + "config.json"); 
     } 
+0

爲什麼你使用'File.seperator'?據我所知,當你使用「/」時,java自己使用正確的分隔符。此外,驗證器似乎與[this one]相當(http://www.mkyong.com/java/how-to-detect-os-in-java-systemgetpropertyosname/);) – MalaKa

1

建立在任何操作系統隱藏文件有關Windows和其他實際支持隱藏文件屬性的操作系統,請參閱this question。甚至有多種方法可以做到這一點。

對於Unix/Linux,名稱以點開頭的文件和文件夾被認爲是隱藏的(例如.ssh)。這些默認情況下不可見。當然,用戶可以在一次瀏覽器中看到它們「顯示隱藏文件」,或者使用-a代替ls。儘管如此,由於方便的原因,這應該是足夠的。