java 使用带有完整路径的 FileWriter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17718613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:46:19  来源:igfitidea点击:

Using the FileWriter with a full path

javafilejava-iofilewriter

提问by chris yo

I specified the full path of the file location when I created a FileWriter, but I did not see the file being created. I also did not get any error during file creation.

我在创建 FileWriter 时指定了文件位置的完整路径,但是我没有看到正在创建的文件。我在文件创建过程中也没有收到任何错误。

Here's a snippet of my code:

这是我的代码片段:

public void writeToFile(String fullpath, String contents) {
    File file = new File(fullpath, "contents.txt");
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
        bw.write(contents);
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

fullpath is "D:/codes/sources/logs/../../bin/logs". I have searched my whole directory, but I cannot find the file anywhere. If I specify just the filename only [File file = new File("contents.txt");] , it is able to save the contents of the file, but it is not placed on my preferred location.

全路径是"D:/codes/sources/logs/../../bin/logs". 我已经搜索了整个目录,但在任何地方都找不到该文件。如果我只指定文件名 [File file = new File("contents.txt");] ,它可以保存文件的内容,但它不会放在我喜欢的位置。

How can I save the file content to a preferred location?

如何将文件内容保存到首选位置?

UPDATE: I printed the full path using file.getAbsolutePath(), and I am getting the correct directory path. [D:\codes\sources\logs....\bin\logs\contents.txt] But when I look for the file in directory, I cannot find it there.

更新:我使用file.getAbsolutePath() 打印了完整路径,并且得到了正确的目录路径。[D:\codes\sources\logs....\bin\logs\contents.txt] 但是当我在目录中查找文件时,我在那里找不到它。

回答by Kevin Bowersox

Make sure you add trailing backslashes to the path parameter so the path is recognized as a directory. The example provide is for a Windows OS which uses backslashes that are escaped. For a more robust method use the file.separatorproperty for the system.

确保向路径参数添加尾部反斜杠,以便将路径识别为目录。提供的示例适用于使用转义反斜杠的 Windows 操作系统。对于更健壮的方法,请使用file.separator系统的属性。

Works

作品

writeToFile("D:\Documents and Settings\me\Desktop\Development\",
                "this is a test");

Doesn't Work

不工作

writeToFile("D:\Documents and Settings\me\Desktop\Development",
                "this is a test");

File Separator Example

文件分隔符示例

String fs = System.getProperty("file.separator");
String path = fs + "Documents and Settings" + fs + "me" + fs
        + "Desktop" + fs + "Development" + fs;
writeToFile(path, "this is a test");