下面的代码没有生成文件(我在任何地方都看不到该文件)。遗漏了什么?
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();
}
发布于 2013-04-02 09:29:07
我认为你的期望和现实不匹配(但它们什么时候会匹配;)
基本上,您认为文件写入的位置和实际写入文件的位置并不相等(嗯,也许我应该写一个if
语句;)
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) {
}
}
}
}
还要注意,您的示例将覆盖任何现有文件。如果要将文本附加到文件,则应改为执行以下操作:
writer = new BufferedWriter(new FileWriter(logFile, true));
发布于 2013-12-04 17:48:00
我想对MadProgrammer的回答补充一点。
在多行写入的情况下,当执行命令时
writer.write(string);
可以注意到在写入的文件中省略或跳过换行符,即使它们在调试期间出现或者如果相同的文本被打印到终端上,
System.out.println("\n");
因此,整个文本作为一大块文本出现,这在大多数情况下是不可取的。换行符可以依赖于平台,因此最好使用以下命令从java系统属性中获取此字符
String newline = System.getProperty("line.separator");
然后使用newline变量而不是"\n“。这将以您想要的方式获得输出。
发布于 2014-04-07 03:54:54
在java 7中现在可以做
try(BufferedWriter w = ....)
{
w.write(...);
}
catch(IOException)
{
}
并且w.close将会自动完成
https://stackoverflow.com/questions/15754523
复制相似问题