Victor Laerte
Victor Laerte

Reputation: 6556

How to create a hidden file in any OS using Java

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

Upvotes: 2

Views: 9953

Answers (2)

Victor Laerte
Victor Laerte

Reputation: 6556

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

Upvotes: 2

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21778

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.

Upvotes: 1

Related Questions