0

I'm on a mac with a script that's writing files to the Documents folder. But I want to be able to write it where I can send it to my friends and they don't have to change the file's path.

File myFile = new File("Users/MyName/Documents/Test/user.text/");

Is there a way where I can make it relative where I don't have to switch around the MyName to whatever the next person PC's name is?

Tyler Moen
  • 81
  • 5

2 Answers2

0

The system property 'user.home' is the magic you're looking for. Unfortunately, there is no OS-agnostic way to determine 'the documents' folder, probably because that is not a universal concept.

You can always just do a quick check if it is there, and if so, use it. Also, there's a new file API, I suggest you use that.

Putting it together:

Path p = Paths.get(System.getProperty("user.home"));
Path candidate = p.resolve("Documents");
if (!Files.isDirectory(candidate)) candidate = p.resolve("My Documents");
if (!Files.isDirectory(candidate)) candidate = p;
p = p.resolve("Test").resolve("user.text");
Files.createDirectories(p.getParent());
Files.write(p, "Hello!");
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • That exact one didn't work but I changed it around for me that worked. Here's the link, it's kinda messy though. [GDrive] (https://drive.google.com/drive/folders/11uDBk0rMae9mHziu18gHIXSpEC2w-iyE?usp=sharing) , https://drive.google.com/drive/folders/11uDBk0rMae9mHziu18gHIXSpEC2w-iyE?usp=sharing – Tyler Moen Aug 04 '20 at 03:00
0

For anyone who's having trouble with @rzwitserloot answer with the ("user.home") solution, Here's what works for me. It's a little messy but it's what works.

public class WritingFile {

    static String data = "This is THe DATA in the output file from a jar. Did it work!?!!";
    //static String paths;
    static String full;
    //static String tester = "/Users/226331/Documents/Test/filesname.txt/";
    public static void main(String[] args) {
        
        pathMaker();
        makeFile();
    }

    public static void pathMaker() {
        //Path path = new Paths.get("test.txt");
        String paths = System.getProperty("user.home");
        System.out.println(paths);
        //System.getenv(paths);
        //System.out.println(paths);
        
        full = paths + "/Documents/Test/filesname.txt/";
        System.out.println(full);
    }
    public static void makeFile() {
        try {
              // Creates a FileWriter
                File myFile = new File(full);
            FileWriter output = new FileWriter(myFile);

              // Writes the string to the file
              output.write(data);

              // Closes the writer
              output.close();
            }

            catch (Exception e) {
              e.getStackTrace();
              e.printStackTrace();
            }
    }
    
}
Tyler Moen
  • 81
  • 5