简体   繁体   English

Java - 如何将文件写入指定的目录

[英]Java - how do I write a file to a specified directory

I want to write a file results.txt to a specific directory on my machine (Z:\\results to be precise). 我想将文件results.txt写入我机器上的特定目录(Z:\\结果是准确的)。 How do I go about specifying the directory to BufferedWriter/FileWriter? 如何指定BufferedWriter / FileWriter的目录?

Currently, it writes the file successfully but to the directory where my source code is located. 目前,它成功写入文件,但是写入源代码所在的目录。 Thanks 谢谢

    public void writefile(){

    try{
        Writer output = null;
        File file = new File("results.txt");
        output = new BufferedWriter(new FileWriter(file));

        for(int i=0; i<100; i++){
           //CODE TO FETCH RESULTS AND WRITE FILE
        }

        output.close();
        System.out.println("File has been written");

    }catch(Exception e){
        System.out.println("Could not create file");
    }
}

You should use the secondary constructor for File to specify the directory in which it is to be symbolically created. 您应该使用File辅助构造函数来指定以符号方式创建它的目录。 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. 希望能帮助到你。

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. 您需要在Windows中加倍反斜杠,因为反斜杠字符本身是Java文字字符串中的转义。

For POSIX system such as Linux, just use the default file path without doubling the forward slash. 对于诸如Linux之类的POSIX系统,只需使用默认文件路径而不会使正斜杠加倍。 this is because forward slash is not a escape character in Java. 这是因为正斜杠不是Java中的转义字符。

File file = new File("/home/userName/Documents/results.txt");

只需将完整目录位置放在File对象中即可。

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

最佳做法是在路径中使用File.separator。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM