简体   繁体   English

在无限循环中使用BufferedWriter

[英]Using BufferedWriter in an infinite loop

Is it possible for me to use a BufferedWriter (or any writer class for that matter) to output a new line to a text file during each iteration of an infinite loop until the program is stopped? 在无限循环的每次迭代期间,直到程序停止为止,我是否可以使用BufferedWriter(或与此相关的任何writer类)将新行输出到文本文件? To my understanding, the BufferedWriter.close() command must be called for the text to be saved onto the file, but if the writer is closed within the loop, the program will throw an exception - obviously, if the writer is set to close outside the loop, the statement is unreachable. 据我了解,必须调用BufferedWriter.close()命令才能将文本保存到文件中,但是如果writer在循环中关闭,则程序将引发异常-显然,如果将writer设置为close在循环之外,该语句不可访问。 Thanks in advance for any help. 在此先感谢您的帮助。

Here's the relevant code: 以下是相关代码:

             int count = 0;
             BufferedWriter out = new BufferedWriter(new FileWriter("myTextFile.txt"));
             while (true) 
             {

                if(count == 0){
                    out.write(myString);
                    out.newLine();
                    System.out.println(myString);
                } else {
                    out.append(myString);
                    out.newLine();
                    System.out.println(myString);

                }
                System.out.println("count = " + count);
                count++;
                out.flush();
                out.close();                   
             }

If you just want to make sure all data is written to file, flush will do it. 如果您只想确保所有数据都已写入文件,则flush会这样做。 Close is mostly to release the resource, especially if you are calling flush explicitly Close主要用于释放资源,尤其是在显式调用flush的情况下

flush - Flushes the stream. flush-刷新流。

close - Closes the stream, flushing it first. close-关闭流,先冲洗它。 Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. 流关闭后,进一步的write()或flush()调用将导致引发IOException。 Closing a previously closed stream has no effect. 关闭先前关闭的流无效。

More info: http://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html 更多信息: http : //docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html

You should use Flush method and extract your close in the finalize() method. 您应该使用Flush方法,并在finalize()方法中提取close

Using Flush will allow you to see the result in your text file while your app write in it. 使用Flush将允许您在应用程序写入文本文件时在文本文件中查看结果。

When you stop your application, the GC will call finalize method and close the stream. 当您停止应用程序时,GC将调用finalize方法并关闭流。

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

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