简体   繁体   English

在Java中创建.txt文件并更改其目录

[英]Creating a .txt File and Changing its Directory in Java

I am creating a .txt file with this: 我正在创建一个.txt文件:

FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);

And I am writing something in it. 我正在写一些东西。 But I want to also determine its directory. 但我还想确定其目录。 For example, my workspace is under C, but I want to create .txt under D. How can I do that? 例如,我的工作区在C下,但是我想在D下创建.txt。我该怎么做?

FileWriter fstream = new FileWriter("D:/out.txt");
BufferedWriter out = new BufferedWriter(fstream);

When give the path "out.txt" as argument, file is created in the current directory. 当将路径“ out.txt”作为参数时,将在当前目录中创建文件。 If you want to create file in another location you have to give it's absolute path as argument. 如果要在其他位置创建文件,则必须提供其绝对路径作为参数。 Note that in windows directory separator is \\ (backslash) and if you're using windows path should be "D:\\\\out.txt" . 请注意,在Windows目录中,分隔符为\\ (反斜杠),如果您使用Windows,则路径应为"D:\\\\out.txt" Why 2 slashes? 为什么2个斜杠? because in Java slash is a special symbol (for example \\n is new line symbol) and should be escaped. 因为在Java中,斜杠是特殊符号(例如\\n是换行符),应将其转义。

FileWriter fstream = new FileWriter("D:\\out.txt");

I am assuming you mean Directory not Direction , as pointed out by codaddict. 正如codaddict所指出的,我假设您的意思是Directory而不是Direction You can take a look at the FileUtils.moveFileToDirectory() if you want to move the file. 如果要移动文件,可以查看FileUtils.moveFileToDirectory()

If you want to create another copy (meaning 2 files), just do something like so: 如果要创建另一个副本(意味着2个文件),请执行以下操作:

FileWriter fstream = new FileWriter("D:\\out.txt");
BufferedWriter out = new BufferedWriter(fstream);

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

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