Java - 如何将文件写入指定的目录 [英] Java - how do I write a file to a specified directory

查看:612
本文介绍了Java - 如何将文件写入指定的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个文件result.txt写入我机器上的特定目录(Z:\results,以确切地说)。如何指定目录到BufferedWriter / FileWriter?

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?

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

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


推荐答案

使用:

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

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

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

对于诸如Linux的 POSIX 系统,只需使用默认文件路径即可将正斜杠加倍。这是因为正斜杠不是Java中的转义字符。

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

这篇关于Java - 如何将文件写入指定的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆