KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > TextCutter


1 import java.io.*;
2 import java.util.*;
3
4 // Example (tested), cf. showUsage at end:
5
/*
6 > cat foo.txt
7 1234567890
8 abcdefghij
9 1234567890
10 abcdefghij
11 >
12 > java TextCutter -f foo.txt -r "0" "MM" -s "3" "M" "ZZZ" -o bar.txt -f foo.txt -a bar.txt
13 > cat bar.txt
14 12ZZZM
15 abcdefghij
16 12ZZZM
17 abcdefghij
18 1234567890
19 abcdefghij
20 1234567890
21 abcdefghij
22 >
23 */

24
25 /**
26  * Replace string delimited regions in text files, multiple replacements at once.
27  * Installer tool to setup configuration files.
28  *
29  * @author <a HREF="mailto:ulf@webman.de">Ulf Goldammer</a>
30  * @version $Revision: 1.2 $
31  **/

32 public class TextCutter
33 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
34
{
35         boolean inmatch;
36         String JavaDoc start, stop, subst;
37         TextCutter pred;
38         
39     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
40
TextCutter() { }
41     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
42

43     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
44
private TextCutter( TextCutter predecessor, String JavaDoc start, String JavaDoc stop, String JavaDoc subst) {
45     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
46
if ( stop.length() == 0 ) { System.err.println( "Emtpy stop delimiter string is illegal."); System.exit( 1 ); }
47         this.pred = predecessor; this.start = start; this.stop = stop; this.subst = subst;
48     }
49     
50     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
51
private TextCutter( TextCutter predecessor, String JavaDoc start, String JavaDoc subst) {
52     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
53
if ( start.length() == 0 ) { System.err.println( "Emtpy search string is illegal."); System.exit( 1 ); }
54         this.pred = predecessor; this.start = start; this.stop = null; this.subst = subst;
55     }
56     
57
58     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
59
private void transform( String JavaDoc inFileName, String JavaDoc outFileName, boolean append) {
60     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
61
BufferedReader in = null;
62         BufferedWriter out = null;
63         String JavaDoc line = null;
64
65         try {
66             if ( inFileName == null ) throw new IOException( "No input file specified.");
67             
68             if ( (new File( inFileName )).getCanonicalPath().equals( (new File( outFileName )).getCanonicalPath() ) )
69                 throw new IOException( "Target file is same as source.");
70                 
71             out = new BufferedWriter( new FileWriter( outFileName, append ) );
72             in = new BufferedReader( new FileReader( inFileName ) );
73             
74             while ( (line = in.readLine()) != null ) {
75                 line = cutLine( line + "\n" );
76                 out.write( line );
77                 // out.write( "\n" );
78
}
79             return;
80         }
81         catch ( IOException e ) { System.err.println( e.getMessage() ); }
82         finally {
83             try { if ( out != null ) out.close(); } catch ( IOException e ) { System.err.println( e.getMessage()); }
84             try { if ( in != null ) in.close(); } catch ( IOException e ) { System.err.println( e.getMessage()); }
85         }
86         System.exit( 2 );
87     }
88
89     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
90
private String JavaDoc cutLine( String JavaDoc line) {
91     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
92

93         // let predecessor transform the line
94

95         if ( pred != null ) line = pred.cutLine( line );
96         
97         // let this object transform the line
98

99         if ( start == null ) return line;
100         
101         int p = 0, q = 0;
102         while ( p >= 0 ) {
103             if ( ! this.inmatch ) {
104                 p = line.indexOf( start, p );
105                 if ( p >= 0 ) {
106                     line = line.substring( 0, p ) + subst + line.substring( p + start.length() );
107                     p += subst.length();
108                     if ( stop != null ) this.inmatch = true;
109                 }
110             }
111             else {
112                 q = p;
113                 p = line.indexOf( stop, p );
114                 if ( p >= 0 ) {
115                     line = line.substring( 0, q ) + line.substring( p + stop.length() );
116                     p = q;
117                     this.inmatch = false;
118                 }
119                 else {
120                     line = line.substring( 0, q);
121                 }
122             }
123         }
124         return line;
125     }
126     
127     
128     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
129
public void start( String JavaDoc args ) {
130     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
131
String JavaDoc[] argList = new String JavaDoc[] {""};
132         try {
133             Vector tokens = new Vector();
134             StreamTokenizer st = new StreamTokenizer( new StringReader( args));
135             st.resetSyntax(); // NECCESSARY whenever using own definitions!
136
st.whitespaceChars(0, ' ');
137             st.wordChars('\u0021', '\u00FF');
138             st.quoteChar('\'');
139             st.quoteChar('"');
140             st.eolIsSignificant(false);
141
142             while( st.nextToken() != StreamTokenizer.TT_EOF) {
143                 switch( st.ttype) {
144                     case '"':
145                     case '\'':
146                     case StreamTokenizer.TT_WORD: tokens.add( st.sval);
147                         break;
148                 }
149             }
150             argList = new String JavaDoc[ tokens.size() ];
151             for( int i = tokens.size(); i >= 0; i-- ) argList[i-1] = (String JavaDoc) tokens.elementAt(i-1);
152
153         }
154         catch ( IOException e ) { System.err.println( e.getMessage()); System.exit(9); }
155         start( argList );
156     }
157
158
159     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
160
public void start( String JavaDoc[] args ) {
161     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
162

163         if ( args.length < 1 ) { showUsage(); System.exit( 0 ); }
164         
165         int l = 0;
166         int u = 0;
167         TextCutter tc = new TextCutter();
168         String JavaDoc inFileName = null;
169
170         try {
171             while ( l < args.length ) {
172                 u = 0;
173                 if (args[l].equals("-h")) { showUsage(); System.exit( 0 ); u = 1;}
174                 if (args[l].equals("-f")) { inFileName = args[l+1]; u = 2; }
175                 if (args[l].equals("-o")) { tc.transform( inFileName, args[l+1], false); u = 2; tc = new TextCutter(); }
176                 if (args[l].equals("-a")) { tc.transform( inFileName, args[l+1], true); u = 2; tc = new TextCutter(); }
177                 if (args[l].equals("-s")) {
178                     tc = new TextCutter( tc, args[l+1], args[l+2], args[l+3] );
179                     u = 4;
180                 }
181                 if (args[l].equals("-r")) {
182                     tc = new TextCutter( tc, args[l+1], args[l+2] );
183                     u = 3;
184                 }
185                 
186                 if ( u < 1 ) {
187                     System.err.println("Unknown option '" + args[l] + "'.\n");
188                     showUsage();
189                     System.exit( 1 );
190                 }
191                 l += u;
192             }
193         }
194         catch ( ArrayIndexOutOfBoundsException JavaDoc aob ) {
195             System.err.println( "Missing argument. Try '-h' for help.");
196             System.exit( 1 );
197         }
198     }
199     
200
201     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
202
public static void main( String JavaDoc[] args ) {
203     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
204

205         new TextCutter().start( args );
206         
207     }
208
209
210     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
211
private void showUsage() {
212     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
213
System.out.println("\nDo text replacements in files.");
214
215         System.out.println("java TextCutter <commands>");
216         System.out.println("where <commands> is sequence of");
217         System.out.println(" -f FILE : read FILE");
218         System.out.println(" -o FILE : process read text and output to FILE, then reset '-s' and '-r'");
219         System.out.println(" -a FILE : process read text and append to FILE, then reset '-s' and '-r'");
220         System.out.println(" -s STRING1 STRING2 STRING3 : substitute regions delimited by STRING1 and STRING2 by STRING3");
221         System.out.println(" -r STRING1 STRING2 : replace every STRING1 by STRING2");
222         System.out.println("");
223     }
224
225 }
226
Popular Tags