2

I am using ObjectOutputStream and ObjectInputStream to read and write data that needs to be stored in between program runs. My question is if there is a proper place to create these files. At the moment I use the following code to find the user's Documents folder.

String myDocuments = null;

        try {
            Process p = Runtime.getRuntime()
                    .exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal");
            p.waitFor();

            InputStream in = p.getInputStream();
            byte[] b = new byte[in.available()];
            if (in.read(b) == 0) myDocuments = JOptionPane.showInputDialog(this,
                    "A fatal error has occurred. \n Please provide your documents folder.");
            else {

                myDocuments = new String(b);
                myDocuments = myDocuments.split("\\s\\s+")[4];
            }
            in.close();

            Log.logLine(myDocuments);

        } catch (Throwable t) {
            t.printStackTrace();
        }

Is this okay as a practice, and if not where should I be storing this information? Also is there a way to do this while still allowing for the application to run a different OS as I am aware that the current method only works with Windows OS.

Parzavil
  • 388
  • 3
  • 13
  • You could use the temp folder if it's nice, but not required, to have this data available in the next run. – Lino Jun 16 '21 at 10:34
  • 1
    The program is meant to work for long periods of time between syncing with a central database. It really needs to have the data persist. – Parzavil Jun 16 '21 at 10:35
  • Related: https://stackoverflow.com/questions/11113974/what-is-the-cross-platform-way-of-obtaining-the-path-to-the-local-application-da – Turamarth Jun 16 '21 at 10:46

1 Answers1

0

I guess it depends on your requirements. Something that should work on every(?) OS is using the application's own folder (or a sub folder of that):

String dir = System.getProperty("user.dir");
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
reden
  • 968
  • 7
  • 14
  • 3
    `String dir = System.getProperty("user.dir");` is probably shorter and more explicit. – Olivier Grégoire Jun 16 '21 at 10:49
  • This should not have been accepted as an answer, it is terrible practice. The user directory is not your free domain to litter in. Every operating system has additional folders such as Program Data and AppData directories on Windows, or Application Support on macOS; use those. – Nick Botticelli Mar 29 '23 at 22:42