简体   繁体   English

使用System.out.println打印时无法写入Java中的文件

[英]Cannot write into a file in java as it is printing using System.out.println

File output=new File("C:\\\\MDU-1617-CSJ0098\\\\web\\\\products.txt");
BufferedWriter writer1 = new BufferedWriter(new FileWriter(output));               
while(q_set2.next()) {
    String s = String.valueOf(q_set2.getInt(1));
    System.out.print(s);
    writer1.write(s);
    writer1.newLine();
}

and the ouput is run: 123456BUILD SUCCESSFUL (total time: 0 seconds) 并且运行输出:123456BUILD SUCCESSFUL(总时间:0秒)

But in file there is no data 但是文件中没有数据

This is what the write method does: write方法的作用:

Ordinarily this method stores characters from the given array into this stream's buffer, flushing the buffer to the underlying stream as needed. 通常,此方法将给定数组中的字符存储到此流的缓冲区中,并根据需要将缓冲区刷新到基础流。

So, it writes to buffer rather than directly writing to file. 因此,它写入buffer而不是直接写入文件。 To make the buffer flush , you need to either call flush or close method, eg: 要使缓冲区flush ,您需要调用flushclose方法,例如:

File output = new File("C:\\\\MDU-1617-CSJ0098\\\\web\\\\products.txt");
BufferedWriter writer1 = new BufferedWriter(new FileWriter(output));
while (q_set2.next()) {
    String s = String.valueOf(q_set2.getInt(1));
    System.out.print(s);
    writer1.write(s);
    writer1.newLine();
}
writer1.close();

close() calls flush() internally and hence, you don't need to call flush() explicitly in this case (here's the Javadoc ). close()内部调用flush() ,因此,在这种情况下,您无需显式调用flush() (这是Javadoc )。

When you call writer1.write(s) , you're not actually printing anything in your file, you're gathering data into memory. 调用writer1.write(s) ,实际上并没有在文件中打印任何内容,而是将数据收集到内存中。 Once you've gathered all the data, you can write all of it at once into your file by calling flush() . 收集完所有数据后,您可以通过调用flush()将所有数据一次性写入文件中。

This is because writing into a file is a costly operation, so BufferedWriter is designed in such a way that that it facilitates writing all data at once instead of writing it in chunks. 这是因为写入文件是一项昂贵的操作,因此BufferedWriter的设计方式使它便于一次写入所有数据,而不是分块写入。

That's why you need to flush the stream. 这就是为什么您需要冲洗流。

Docs 文件

public void flush() throws IOException 公共无效flush()引发IOException

Flushes the stream. 冲洗流。

Now eiter you can... 现在,您可以...

  1. Call flush() method or 调用flush()方法或
  2. close the stream. 关闭流。 This will automatically call flush() method. 这将自动调用flush()方法。

.

File output=new File("C:\\\\MDU-1617-CSJ0098\\\\web\\\\products.txt");
         BufferedWriter writer1 = new BufferedWriter(new FileWriter(output));               

while(q_set2.next())  {
    String s=String.valueOf(q_set2.getInt(1));
    System.out.print(s);
    writer1.write(s);
    writer1.newLine();
}

writer1.flush(); // or writer1.close();

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

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