Java - how do I write a file to a specified directory

后端 未结 4 1349
温柔的废话
温柔的废话 2020-12-24 13:25

I want to write a file results.txt to a specific directory on my machine (Z:\\results to be precise). How do I go about specifying the directory to BufferedWriter/FileWriter

相关标签:
4条回答
  • 2020-12-24 13:44

    Use:

    File file = new File("Z:\\results\\results.txt");
    

    You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.

    For POSIX system such as Linux, just use the default file path without doubling the forward slash. this is because forward slash is not a escape character in Java.

    File file = new File("/home/userName/Documents/results.txt");
    
    0 讨论(0)
  • 2020-12-24 13:46

    The best practice is using File.separator in the paths.

    0 讨论(0)
  • 2020-12-24 13:54

    You should use the secondary constructor for File to specify the directory in which it is to be symbolically created. This is important because the answers that say to create a file by prepending the directory name to original name, are not as system independent as this method.

    Sample code:

    String dirName = /* something to pull specified dir from input */;
    
    String fileName = "test.txt";
    File dir = new File (dirName);
    File actualFile = new File (dir, fileName);
    
    /* rest is the same */
    

    Hope it helps.

    0 讨论(0)
  • 2020-12-24 14:00

    Just put the full directory location in the File object.

    File file = new File("z:\\results.txt");
    
    0 讨论(0)
提交回复
热议问题