为什么我的 fileOutputstream 忽略附加“true”旗帜?
我正在尝试包装 FileinputStream 并在包装类“Amigo”中更改 Parent 的 close 方法。正如您在代码中看到的,我使用默认的 FileInputStream 对象在使用 .close() 方法的情况下在文件末尾写入一些数据。但是,尽管我在 fileOutputStream 字段中使用“append”到“true”标志,但我的程序仍然会覆盖文件中的数据。为什么会出现这种情况呢?
public class AmigoOutputStream extends FileOutputStream{
public static String fileName = "C:\\Users\\Егор\\IdeaProjects\\JavaRushTasks\\2.JavaCore\\src\\com\\javarush\\task\\task18\\task1813\\r.txt";
private FileOutputStream fileOutputStream = new FileOutputStream(fileName,true);
private static final String JAVA_RUSH = "JavaRush © All rights reserved.";
public AmigoOutputStream(FileOutputStream name) throws FileNotFoundException {
super(String.valueOf(name),true);
}
public static void main(String[] args) throws IOException {
new AmigoOutputStream(new FileOutputStream(fileName)).close();
}
@Override
public void close() throws IOException {
fileOutputStream.flush();
fileOutputStream.write(JAVA_RUSH.getBytes());
fileOutputStream.close();
}
}
I m trying to wrap FileinputStream and change close method of Parent in my wrapper class "Amigo". As u can see in code, i use default FileInputStream object to write some data in end of file in case of using .close() method. But, despite that i use "append" to "true" flag in the fileOutputStream field, my programm is still overwrites data in file. Why is this happens?
public class AmigoOutputStream extends FileOutputStream{
public static String fileName = "C:\\Users\\Егор\\IdeaProjects\\JavaRushTasks\\2.JavaCore\\src\\com\\javarush\\task\\task18\\task1813\\r.txt";
private FileOutputStream fileOutputStream = new FileOutputStream(fileName,true);
private static final String JAVA_RUSH = "JavaRush © All rights reserved.";
public AmigoOutputStream(FileOutputStream name) throws FileNotFoundException {
super(String.valueOf(name),true);
}
public static void main(String[] args) throws IOException {
new AmigoOutputStream(new FileOutputStream(fileName)).close();
}
@Override
public void close() throws IOException {
fileOutputStream.flush();
fileOutputStream.write(JAVA_RUSH.getBytes());
fileOutputStream.close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
main
内的new FileOutputStream(fileName)
行将擦除文件,并且该行在new FileOutputStream(fileName,true)
之前运行,该文件位于班级。您还创建了一个具有不寻常名称的新文件 - 设置为
String.valueOf(name)
。您可能需要这样的东西,它允许调用者指定文件,并意味着 AmigoOutputStream 始终向某个文件发送额外的字节:The line with
new FileOutputStream(fileName)
insidemain
will wipe the file and that runs beforenew FileOutputStream(fileName,true)
which is inside the class.You are also creating a new file which has an unusual name - set to
String.valueOf(name)
. You may want something like this which allows caller to specify the file and meansAmigoOutputStream
always sends extra bytes to some file: