2011-12-13 46 views
6

我写一个简单的函数是这样的:改写成一个文件

private static void write(String Swrite) throws IOException { 
    if(!file.exists()) { 
     file.createNewFile(); 
    } 
    FileOutputStream fop=new FileOutputStream(file); 
    if(Swrite!=null) 
     fop.write(Swrite.getBytes()); 
    fop.flush(); 
    fop.close(); 
} 

每次我叫它,它重写,然后我刚拿到写在最后的项目。我怎样才能改变它不重写?变量file全局定义为File

回答

3

在您FileOutputStreamconstructor,你需要添加boolean append参数。然后,它看起来就像这样:

FileOutputStream fop = new FileOutputStream(file, true); 

这告诉FileOutputStream,它应该将文件添加的不是清除和重写其目前所有的数据。

+0

是的,这是正确的,谢谢 – seventeen

+0

,但仍然有点问题,它没有任何空间,它写在最后一个字符后,所以它不会被读取,我怎么能让它在每次写后给一个空间? – seventeen

+1

chang'fop.write(...)'到'fop.write(... +“\ n”)' – Jon

2

使用以作为参数追加标志的承包商。

FileOutputStream fop=new FileOutputStream(file, true); 
+0

,这是正确的,感谢 – seventeen

+0

但还是有点问题完成的,它没有做任何的空间,最后一个字符写入正是这样它会不可读,我怎么能让它在每次写入后给出空间 – seventeen

+0

@MostafaAlli:然后**写入空格 –

0

尝试RandomAccessFile如果您尝试写入某些字节偏移量。

+1

它不一定是某个偏移量,他只是想要附加文件。 – Jon

0

拖参数构造函数是正确的。它是多余的:

if(!file.exists()) { 
     file.createNewFile(); 
} 

构造函数将为您做。

1

您应该在append模式下打开该文件,默认情况下FileOutputStreamwrite模式下打开文件。而且你也无需检查的file存在,这将隐含地被FileOutputStream

private static void write(String Swrite) throws IOException { 
    FileOutputStream fop=new FileOutputStream(file, true); 
    if(Swrite!=null) 
     fop.write(Swrite.getBytes()); 
    fop.flush(); 
    fop.close(); 
}