O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Expanding and Compressing Tabs

Problem

You need to convert space characters to tab characters in a file, or vice versa. You might want to replace spaces with tabs to save space on disk, or go the other way to deal with a device or program that can’t handle tabs.

Solution

Use my Tabs class or its subclass EnTab.

Discussion

Example 3-5 is a listing of EnTab , complete with a sample main program. The program works a character at a time; if the character is a space, we see if we can coalesce it with previous spaces to output a single tab character. This program depends on the Tabs class, which we’ll come to shortly. The Tabs class is used to decide which column positions represent tab stops and which do not. The code also has several Debug printouts. (Debug was introduced in Section 1.12.)

Example 3-5. Entab.java

import com.darwinsys.util.Debug; import java.io.*; /** entab- replace blanks by tabs and blanks. * Transmuted from K&R Software Tools book into C. * Transmuted again, years later, into Java. */ public class EnTab { /** Main program: just create an EnTab program, and pass * the standard input or the named file(s) through it. */ public static void main(String[] argv) throws IOException { EnTab et = new EnTab(8); if (argv.length == 0) // do standard input et.entab(new BufferedReader( new InputStreamReader(System.in))); else for (int i=0; i<argv.length; i++) { // do each file et.entab(new BufferedReader(new FileReader(argv[i]))); } } /** The Tabs (tab logic handler) */ protected ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required