这是我的代码:
import java.io.*;
public class WrappedWriter extends PrintWriter {
public WrappedWriter(OutputStream o){
super(o);
}
public WrappedWriter(File f) throws FileNotFoundException{
super(f);
}
public WrappedWriter(String s) throws FileNotFoundException{
super(s);
}
}
正如您所看到的,PrintWriter 正在由此类进行扩展。在 WrappedWriter 类中,我继续创建一个字符串,可以将其打印到终端或写入文件。有人告诉我,为了将其写入文件,我必须在此处的第二个和第三个构造函数中插入一些内容。我已经放置了 super() 来调用父类,但我试图找出如何通过在构造函数中键入代码来编写最终到达文件 f 的字符串。有人能指出我正确的方向吗?这是当我在交互模式下输入某些输入时应该发生的情况。
WrappedWriter out = new WrappedWriter(System.out)
out = new WrappedWriter("gettysburg.txt");
out.println("Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.")
out.close();
输入 out.close 后,应该将字符串写入文件 gettysburg.txt,但它没有这样做。
最佳答案
I am told that in order to write to a file, I have to insert something into the second and third constructor[s]
您被误导了。这两个构造函数都会导致编写器写入文件。请参阅 PrintWriter 的 Javadoc。
关于java - 如何重写构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22262782/