Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java文本文件的每个页面的开头添加一个标题_Java_Text_Printing - Fatal编程技术网

在Java文本文件的每个页面的开头添加一个标题

在Java文本文件的每个页面的开头添加一个标题,java,text,printing,Java,Text,Printing,我试图在Java中为每个页面的开头添加一个标题。我也正在将控制台输出打印到文件中。我能找到的所有示例都是PDF文件,但我需要打印到文本文件,以便以后进行数据传输,并使用我无法使用的iText。任何建议都会很棒。以下是我目前打印的方式: PrintStream out = new PrintStream(new FileOutputStream("example.txt")); System.setOut(out); 我假设您将使用固定宽度的字符(其他任何字符都将非常复杂…) 这是一个简

我试图在Java中为每个页面的开头添加一个标题。我也正在将控制台输出打印到文件中。我能找到的所有示例都是PDF文件,但我需要打印到文本文件,以便以后进行数据传输,并使用我无法使用的iText。任何建议都会很棒。以下是我目前打印的方式:

  PrintStream out = new PrintStream(new FileOutputStream("example.txt"));
  System.setOut(out);

我假设您将使用固定宽度的字符(其他任何字符都将非常复杂…)

这是一个简单的实现,您可以从这里进行调整。我认为它工作得相当不错,但你应该彻底测试它,还要处理单词比一行长的情况,如果页眉比页面长,可能是一个更好的例外:

public class PagePrinter {

    private final PrintStream printer;
    private final int pageWidth;
    private final int pageLength;

    private int currWidth = 0;
    private int currLine = 0;
    private int currPage = 1;

    private boolean inPageHeader = false;

    /**
     * @param printer
     *            - print stream to print to
     * @param pageWidth
     *            - in characters
     * @param pageLength
     *            - in lines, includes the length of the header
     */
    public PagePrinter(PrintStream printer, int pageWidth, int pageLength) {
        this.printer = printer;
        this.pageLength = pageLength;
        this.pageWidth = pageWidth;
    }

    public void print(String str) {
        // replace tabs with spaces
        // may need to replace other chars that don't translate to 1 char when printed
        str = str.replace("\t", "    ");
        // split would drop a trailing delimiter so concat extra
        String[] lines = str.concat("\r\n#").split("\\r?\\n");
        // print first
        printWords(lines[0]);
        // print rest excluding the extra
        for (int i = 1; i < lines.length - 1; i++) {
            // re-add delimiter (but keeping track of its affect on the page)
            newline();
            printWords(lines[i]);
        }
    }

    private void printWords(String str) {
        // split would drop a trailing delimiter so concat extra
        String[] words = str.concat(" #").split(" ");
        printWord(words[0]);
        for (int i = 1; i < words.length - 1; i++) {
            // re-add delimiter (but keeping track of its affect on the page)
            if (currWidth < pageWidth) {
                printer.print(" ");
                currWidth++;
            }
            printWord(words[i]);
        }
    }

    /** The smallest unit of appending to the document, */
    private void printWord(String word) {
        // determines when to print a header
        if (currLine == 0 && !inPageHeader) {
            printPageHeader();
        }

        int remainingSpaceOnLine = pageWidth - currWidth;
        if (word.length() < remainingSpaceOnLine) {
            printer.print(word);
            currWidth += word.length();
        } else if (word.length() < pageWidth) {
            newline();
            printWord(word);
        } else {
            // FIXME word is longer than the page width
            // maybe split it with a hyphen and addWord() the parts
            throw new RuntimeException("Word '" + word + "' is longer than line!");
        }
    }

    public void newline() {
        currLine++;
        if (currLine >= pageLength) {
            newPage();
        } else {
            currWidth = 0;
            printer.println();
        }
    }

    public void newPage() {
        if (inPageHeader) {
            throw new RuntimeException("Page header is longer than the page!!!");
        }
        currWidth = 0;
        currLine = 0;
        currPage++;
        printer.println();
    }

    private void printPageHeader() {
        inPageHeader = true;
        myPageHeader();
        inPageHeader = false;
    }

    protected void myPageHeader() {
        print("----- Page " + currPage + " -----\n");
    }


    public static void main(String[] args) {
        PagePrinter test = new PagePrinter(System.out, 40, 10);
        test.print("\tThis is the song that never ends. Yes, it goes on and on my friend. "
                + "Some people started singing it not knowing what it was "
                + "and they'll continue singing it forever just because..."
                + "\n\tThis is the song that never ends. Yes, it goes on and on my friend. "
                + "Some people started singing it not knowing what it was "
                + "and they'll continue singing it forever just because..."
                + "\n\tThis is the song that never ends. Yes, it goes on and on my friend. "
                + "Some people started singing it not knowing what it was "
                + "and they'll continue singing it forever just because.."
                + "\n\tThis is the song that never ends. Yes, it goes on and on my friend. "
                + "Some people started singing it not knowing what it was "
                + "and they'll continue singing it forever just because...");
        test.newPage();
        test.print("This is a new page!");
        test.newline();
        test.print("This is a newline even though part would've fit on the previous!");
    }
}
公共类页面打印机{
私人最终打印流打印机;
私有最终整型页面宽度;
私有最终整型页面长度;
私有int currWidth=0;
私有int currLine=0;
私人网页=1;
私有布尔inPageHeader=false;
/**
*@param打印机
*-要打印到的打印流
*@param pageWidth
*-字符
*@param pageLength
*-在行中,包括收割台的长度
*/
公共页打印机(打印流打印机、int pageWidth、int pageLength){
this.printer=打印机;
this.pageLength=页面长度;
this.pageWidth=页面宽度;
}
公共作废打印(字符串str){
//用空格替换制表符
//可能需要替换打印时无法转换为1个字符的其他字符
str=str.replace(“\t”,”);
//split将删除一个尾随分隔符,以便额外添加
字符串[]行=str.concat(“\r\n#”).split(\\r?\\n”);
//先印
打印字(第[0]行);
//打印剩余部分,不包括额外部分
对于(int i=1;i=页面长度){
newPage();
}否则{
宽度=0;
printer.println();
}
}
public void newPage(){
如果(输入页眉){
抛出新的RuntimeException(“页眉比页面长!!!”;
}
宽度=0;
currLine=0;
currPage++;
printer.println();
}
私有void printPageHeader(){
inPageHeader=true;
myPageHeader();
inPageHeader=false;
}
受保护的无效myPageHeader(){
打印(“----页”+当前页+”----\n”);
}
公共静态void main(字符串[]args){
PagePrinter测试=新的PagePrinter(System.out,40,10);
test.print(“\t这是一首永无止境的歌。是的,我的朋友一直在唱。”
+“有些人开始唱它,却不知道它是什么”
+“他们会一直唱下去,因为……”
+“\n\t这是一首永无止境的歌。是的,我的朋友一直在唱。”
+“有些人开始唱它,却不知道它是什么”
+“他们会一直唱下去,因为……”
+“\n\t这是一首永无止境的歌。是的,我的朋友一直在唱。”
+“有些人开始唱它,却不知道它是什么”
+“他们将永远唱下去,因为……”
+“\n\t这是一首永无止境的歌。是的,我的朋友一直在唱。”
+“有些人开始唱它,却不知道它是什么”
+“他们会一直唱下去,因为……”);
test.newPage();
打印(“这是一个新页面!”);
test.newline();
打印(“这是一条新行,即使零件在上一条上也能安装!”);
}
}

在txt文件中定义“页面开头”。是在几行之后吗?你需要做一些决定。一页有多长?@cjstitles我不太清楚你的情况,但我想说的是,通常避免
System.setOut()
。为什么不直接用
out.println(“”
)打印到您的
PrintStream out
,是因为您已经有很多
System.out.println()
语句,并且不想更改它们?@xtratic感谢您的回复!这就是我想弄明白的。似乎有很多变量,比如他们是否把它打印成字母之类的东西。我确实有很多打印语句,通常带有一组sp