如何写文本文件的Java

以下代码不会生成文件(我无法在任何地方看到该文件)。 什么不见​​了?

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(); } 

我认为你的期望和现实不符(但是他们什么时候有);)

基本上,你认为在哪里写文件和文件实际写在哪里是不相等的(嗯,也许我应该写一个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)); 

我想多加一些MadProgrammer的答案。

在多行写入的情况下,执行命令时

 writer.write(string); 

人们可能会注意到,即使在debugging过程中出现换行符,或者如果相同的文本被打印到terminal上,

 System.out.println("\n"); 

因此,整个文本成为大多数情况下不可取的一大块文本。 换行符可以依赖于平台,所以最好从java系统属性中使用这个字符

 String newline = System.getProperty("line.separator"); 

然后使用换行符而不是“\ n”。 这将以您想要的方式得到输出。

在Java 7现在可以做

 try(BufferedWriter w = ....) { w.write(...); } catch(IOException) { } 

和w.close将自动完成

这不是创build一个文件,因为你从来没有真正创build的文件。 你为它做了一个对象。 创build实例不会创build该文件。

 File newFile = new File("directory", "fileName.txt"); 

你可以这样做来创build一个文件:

 newFile.createNewFile(); 

你可以这样做一个文件夹:

 newFile.mkdir(); 

您可以尝试一个Java库。 FileUtils ,它有很多写入文件的function。

它确实与我合作。 确保在timeLog旁边添加“.txt”。 我在一个用Netbeans打开的简单程序中使用它,并将程序写入主文件夹(构build器和src文件夹所在的位置)。