How to create a hidden file in any OS using Java

故事扮演 提交于 2021-02-08 04:37:53

问题


I have this code trying to create and write in my Json File, but how can I do it Hidden in any OS (Windows or Mac)

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

回答1:


What I did was to creat a OSValidator and for each OS I encode my file and save it in a Application Dir (windows: appdata, mac: Application Suport). It seemed to be the easiest to do.

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");
        }



回答2:


See this question for Windows and other operating systems that actually support the hidden file attribute. There are even multiple ways to do this.

For Unix/Linux, files and folders whose names start with dot are considered hidden (like .ssh, for instance). These are not visible by default. Surely the user can see them in one turns "show hidden files" on for explorer or uses -a for ls. Still, for the reasons like convenience reasons this should be sufficient.



来源:https://stackoverflow.com/questions/14754322/how-to-create-a-hidden-file-in-any-os-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!