用Java打开一个现有文件并关闭它。 [英] Opening an existing file in Java and closing it.

查看:161
本文介绍了用Java打开一个现有文件并关闭它。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能在java中打开一个文件追加数据并关闭很多次。例如:

pre code pre
$变量声明
FileWriter writer1 =新的FileWriter(文件名);

fn1:

writer.append(data - title);

fn2:
while(incomingdata == true){
writer.append(data)
writer.flush();
writer.close()
}

问题在于while循环。该文件关闭,不能再次打开。任何人都可以在这帮助我?

解决方案

建议每次关闭和重新打开文件的答案是非常正确的。

但是,如果你确实需要这样做,那么你可以每次创建一个新的FileWriter。当构造一个FileWriter时,传递true作为第二个参数,以获得一个附加到该文件而不是替换它的文件。像

  FileWriter writer1 = new FileWriter(filename,true); 


Is it possible to open a file a in java append data and close numerous times. For example:

 //---- psuedocode
      //class variable declaration 
      FileWriter writer1 = new FileWriter(filename);

      fn1:

         writer.append(data - title);

      fn2:
       while(incomingdata == true){
         writer.append(data)
         writer.flush();
         writer.close()
        }

The problem lies in the while loop. The file is closed and cant be opened again. Any one can help me in this?

解决方案

The answers that advise against closing and re-opening the file each time are quite correct.

However, if you absolutely have to do this (and it's not clear to me that you do), then you can create a new FileWriter each time. Pass true as the second argument when you construct a FileWriter, to get one that appends to the file instead of replacing it. Like

FileWriter writer1 = new FileWriter(filename, true); 

这篇关于用Java打开一个现有文件并关闭它。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆