如何编写文本文件Java [英] How to Write text file Java
本文介绍了如何编写文本文件Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码不会产生文件(我无法看到该文件)。
缺少什么?
The following code does not produce a file (I can't see the file anywhere). What is missing?
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
Calendar.getInstance().getTime());
File logFile=new File(timeLog);
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
writer.write (string);
//Close writer
writer.close();
} catch(Exception e) {
e.printStackTrace();
}
推荐答案
我认为你的期望和现实不符合(但是他们曾经有过))
I think your expectations and reality don't match (but when do they ever ;))
基本上,你认为文件写在哪里,文件实际写在哪里不等于(嗯,也许我应该写一个如果
statement;))
Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if
statement ;))
public class TestWriteFile {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
File logFile = new File(timeLog);
// This will output the full path where the file will be written to...
System.out.println(logFile.getCanonicalPath());
writer = new BufferedWriter(new FileWriter(logFile));
writer.write("Hello world!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
}
}
另请注意,您的示例将覆盖任何现有文件。如果要将文本附加到文件中,您应该执行以下操作:
Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:
writer = new BufferedWriter(new FileWriter(logFile, true));
这篇关于如何编写文本文件Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文