KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > armedbear > j > ShellTokenizer


1 /*
2  * ShellTokenizer.java
3  *
4  * Copyright (C) 2000-2002 Peter Graves
5  * $Id: ShellTokenizer.java,v 1.1.1.1 2002/09/24 16:08:09 piso Exp $
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20  */

21
22 package org.armedbear.j;
23
24 import java.util.Vector JavaDoc;
25
26 public final class ShellTokenizer
27 {
28     private Vector JavaDoc v = new Vector JavaDoc();
29     private int index;
30
31     public ShellTokenizer(String JavaDoc s)
32     {
33         FastStringBuffer sb = new FastStringBuffer();
34         char quoteChar = 0;
35         int limit = s.length();
36         for (int i = 0; i < limit; i++) {
37             char c = s.charAt(i);
38             if (c == '\\') {
39                 sb.append(c);
40                 if (i < limit-1) {
41                     sb.append(s.charAt(++i));
42                     continue;
43                 }
44             } else if (quoteChar != 0) {
45                 sb.append(c);
46                 if (c == quoteChar)
47                     quoteChar = 0;
48             } else if (c == '\'' || c == '"') {
49                 sb.append(c);
50                 quoteChar = c;
51             } else if (c == ' ' || c == '\t' || c == '=') {
52                 if (sb.length() > 0) {
53                     v.add(sb.toString());
54                     sb.setLength(0);
55                 }
56             } else
57                 sb.append(c);
58         }
59         if (sb.length() > 0)
60             v.add(sb.toString());
61     }
62
63     public boolean hasMoreTokens()
64     {
65         return index < v.size();
66     }
67
68     public String JavaDoc nextToken()
69     {
70         String JavaDoc token = null;
71         if (index < v.size())
72             token = (String JavaDoc) v.get(index++);
73         return token;
74     }
75
76     public String JavaDoc lastToken()
77     {
78         String JavaDoc token = null;
79         if (v.size() > 0)
80             token = (String JavaDoc) v.get(v.size()-1);
81         return token;
82     }
83 }
84
Popular Tags