Program: A Simple Text Formatter

This program is a very primitive text formatter, representative of what people used on most computing platforms before the rise of standalone graphics-based word processors, laser printers, and, eventually, desktop publishing, word processors, and desktop office suites. It simply reads words from a file -- previously created with a text editor -- and outputs them until it reaches the right margin, when it calls println( ) to append a line ending. For example, here is an input file:

It's a nice
day, isn't it, Mr. Mxyzzptllxy?
I think we should
go for a walk.

Given the above as its input, the Fmt program will print the lines formatted neatly:

It's a nice day, isn't it, Mr. Mxyzzptllxy? I think we should go for a
walk.

As you can see, it has fitted the text we gave it to the margin and discarded all the line breaks present in the original. Here’s the code:

import java.io.*; import java.util.*; /** * Fmt - format text (like Berkeley Unix fmt). */ public class Fmt { /** The maximum column width */ public static final int COLWIDTH=72; /** The file that we read and format */ BufferedReader in; /** If files present, format each, else format the standard input. */ public static void main(String[] av) throws IOException { if (av.length == 0) new Fmt(System.in).format( ); else for (int i=0; i<av.length; i++) new Fmt(av[i]).format( ); } /** Construct a Formatter given a filename */ public Fmt(String fname) throws IOException { in = new BufferedReader(new FileReader(fname)); ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.