2017-07-24 133 views
0

我已经注意到输出流类(缓冲输出流)的行为,我想了解它来解决我的问题,即当我创建一个对象在文件中写入文本数据时,它是确定的但尝试与同等级的另一个目的是再次写入正常工作,但与新的缓冲输出流

class writeFile extneds BufferedOutputStream{ 
    public static void main(String arg[]) throws FileNotFoundException, IOException 
{ 

    new writeFile(new FileOutputStream(file)).setComments("hello"); 
    new writeFile(new FileOutputStream(file)).setComments("Hi"); 

} 

    public void setComments(String s) throws IOException 
    { 
     this.write(this.setBytes(s+"\r\n\n")); 
    this.write(this.setBytes("-----------------------------------\r\n\n")); 
    } 

取代以前的文本时执行它,我觉得只是喜字和第一个字是不存在的,因为它与最后一个更换所以为什么当我使用另一个对象来写它从头开始写入的一些文本并在之前替换,并且有任何解决方案,因为当我关闭程序并再次打开它时,它将成为对象的新声明,并将其视为新对象

+0

什么是'setBytes()'?你为什么要执行'BufferedOutputStream'? – shmosel

+3

'new FileOutputStream(file)'打开文件进行写入和截断内容。为什么这让你感到惊讶? –

+0

setBytes是一个将字符串作为参数并将其转换为字节数组的方法,我将其扩展为使用受保护的缓冲区,并在写入之前采用缓冲功能 – user1841718

回答

1

有一个FileOutputStream(String, boolean)构造函数,其中第二个参数是附加。最简单的解决我明白了,改变

new writeFile(new FileOutputStream(file)).setComments("Hi"); 

new writeFile(new FileOutputStream(file, true)).setComments("Hi"); 

我个人认为,这将是最好使用一个OutputStream(和你的writeFile是可能的,例如类)。您应该始终使用close您的资源(您可以使用try-with-resources)。最后,Java命名约定的类都以大写字母开头 - writeFile看起来像是方法名称

try (writeFile fos = new writeFile(new FileOutputStream(file))) { 
    fos.setComments("hello"); 
    fos.setComments("Hi"); 
} 
+0

非常感谢你 – user1841718

+1

并关闭()该文件。 –