[英]Writing to Files : Printwriter Converting Forward Slash to Backslash
Why is Printwriter doing this? 为什么Printwriter这样做?
File file = new File("/files/KA.txt");
writer = new PrintWriter(file);
writer.write("HELLO");
In the above code I keep getting an error that says : 在上面的代码中,我不断收到错误消息:
java.io.FileNotFoundException: \files\KA.txt (The network path was not found)
Except this was not my specified path? 除非这不是我指定的路径? How do I then specify a file to write - usually create a new file and write to this?
然后,我如何指定要写入的文件-通常创建一个新文件并对此进行写入? It also throws errors if KA.txt is not present - I ideally want to create a new file and writer to it.
如果不存在KA.txt,它也会引发错误-理想情况下,我想创建一个新文件并将其写入。
Thanks 谢谢
I ideally want to create a new file and writer to it.
理想情况下,我想创建一个新文件并对其进行写入。
You can simply create a file , 您可以简单地创建一个文件,
PrintWriter writer = new PrintWriter("name.txt", "UTF-8");
writer.println("text");
where UTF-8
is the file encoding. 其中
UTF-8
是文件编码。 and write to the file , remember it overrides if the file exists with the same name 并写入文件,请记住它会覆盖文件是否存在相同名称
The problem is that the parent /files directory doesn't already exist, so you must create it beforehand, using File.mkdirs. 问题是父/ files目录不存在,因此必须事先使用File.mkdirs创建它。
File file = new File("/files/KA.txt");
File parentFile = file.getParentFile();
parentFile.mkdirs();
PrintWriter writer = new PrintWriter(file);
writer.write("HELLO");
writer.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.