我正在编写一个java反编译器。为了给输出一个很好的缩进,我决定编写一个名为TabbedPrintWriter
的类来自动地适当地列出输出。这是代码:
import java.io.OutputStream;
import java.io.PrintWriter;
public class TabbedPrintWriter extends PrintWriter {
private static int indentAmount = 4;
private int indent = 0;
public TabbedPrintWriter(OutputStream out) {
super(out);
}
public TabbedPrintWriter(OutputStream out, boolean autoFlush) {
super(out, autoFlush);
}
@Override
public void println() {
super.println();
for (int i = 0; i <= indentAmount * indent; i++) {
super.write(' ');
}
}
public void indent() {
indent++;
}
public void unindent() {
indent--;
}
}
我还写了一个测试类来测试它:
public class TabbedPrintWriterTest {
public static void main(String[] args) {
TabbedPrintWriter writer = new TabbedPrintWriter(System.out, true);
writer.println("Hello");
writer.indent();
writer.println("Goodbye");
}
}
如果查看代码,每个缩进级别应为四个空格。但是,如果我运行它,我得到这个输出:
Hello
Goodbye
是的,没错。只有一个空间。
为什么会这样?
答案 0 :(得分:0)
在重写代码和调试之后,我终于设法让它工作了:
public class TabbedPrintWriter extends PrintWriter {
private static int indentAmount = 4;
private int indent = 0;
private StringBuilder line = new StringBuilder();
public TabbedPrintWriter(OutputStream out) {
super(out);
}
public TabbedPrintWriter(OutputStream out, boolean autoFlush) {
super(out, autoFlush);
}
@Override
public void println() {
for (int i = 0; i < indentAmount * indent; i++)
line.insert(0, ' ');
super.write(line.toString(), 0, line.length());
line = new StringBuilder();
super.println();
}
@Override
public void write(int c) {
line.append((char) c);
}
@Override
public void write(String s, int off, int len) {
line.append(s, off, len);
}
@Override
public void write(char[] buf, int off, int len) {
line.append(buf, off, len);
}
public void indent() {
indent++;
}
public void unindent() {
indent--;
}
}
基本上,我会在打印出行之前进行行缓冲并插入缩进。现在它正在工作,我不需要社区的帮助,所以主要原因是确保没有人分心试图回答不需要回答的问题。并传播一个工作标签打印作家的话。