【问题标题】:Java - how do I write a file to a specified directoryJava - 如何将文件写入指定目录
【发布时间】:2011-08-13 10:09:29
【问题描述】:

我想将文件 results.txt 写入我机器上的特定目录(准确地说是 Z:\results)。如何指定 BufferedWriter/FileWriter 的目录?

目前,它成功地将文件写入我的源代码所在的目录。谢谢

    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");
    }
}

【问题讨论】:

    标签: java file directory bufferedwriter


    【解决方案1】:

    您应该使用secondary constructor 代替File 来指定要在其中进行符号创建的目录。这很重要,因为通过将目录名称添加到原始名称来创建文件的答案并不像这种方法那样独立于系统。

    示例代码:

    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 */
    

    希望对你有帮助。

    【讨论】:

    • 或者使用System.getProperty("file.separator")
    【解决方案2】:

    用途:

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

    您需要在 Windows 中将反斜杠加倍,因为反斜杠字符本身是 Java 文字字符串中的转义符。

    对于POSIX系统如Linux,直接使用默认文件路径,不加双斜杠即可。这是因为正斜杠在 Java 中不是转义字符。

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 其实需要对反斜杠进行转义: File file = new File("z:\\results.txt");或者只使用常规斜杠 File file = new File("z:/results.txt");
      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2019-11-26
        • 2019-06-16
        • 1970-01-01
        • 1970-01-01
        • 2012-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多