Search code examples
javaappdata

Setting download path to %appdata% and further


In a download (Java) script can you set the location to %appdata%, %home%, ect.? I've tried adding this the script in many different ways but all I come up with are errors. Do I need launch a .bat file before hand to set the directory, cd and everything?


Solution

  • You can set the path to an environment variable using System.getenv() (no .bat script required):

    File dir = new File(System.getenv("APPDATA"), "DataFolder");
    

    To make sure the folder is created:

    if (!dir.exists())
    {
        try
        {
            dir.mkdirs();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    

    To make a file in the folder and make sure it is created:

    File file = new File(dir, "log.txt");
    if (!file.exists())
    {
        try
        {
            file.createNewFile();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }