View Javadoc

1   package cz.cuni.amis.utils;
2   
3   import java.util.Arrays;
4   
5   /**
6    * You will stuff strings into the object and it will check whether the 'limiter'
7    * is present. If so, it will cut the string buffer along the 'limiter' and return
8    * you the parts.
9    * 
10   * @author Jimmy
11   */
12  public class StringCutter {
13  		
14  	private String limiter = "\r\n";
15  	
16  	private StringBuffer buffer = new StringBuffer(200);
17  	
18  	private String[] empty = new String[0];
19  	
20  	/**
21  	 * Default limiter is "\r\n" (windows new line).
22  	 */
23  	public StringCutter() {			
24  	}
25  	
26  	public StringCutter(String limiter) {
27  		this.limiter = limiter;
28  	}
29  	
30  	/**
31  	 * Adding string to the buffer, returning strings if 'limiter' is found.
32  	 * If no limiter is present, returns String[0].
33  	 * @param str
34  	 * @return
35  	 */
36  	public String[] add(String str) {
37  		buffer.append(str);
38  		if (buffer.indexOf(limiter) > 0) {
39  			String bufferString = buffer.toString();
40  			String[] strs = bufferString.split(limiter);
41  			String[] result;
42  			if (bufferString.endsWith(limiter)) {
43  				result = strs;
44  				buffer.delete(0, buffer.length());
45  			} else {
46  				result = Arrays.copyOf(strs, strs.length-1);
47  				buffer.delete(0, buffer.length());
48  				buffer.append(strs[strs.length-1]);
49  			}
50  			return result;
51  		}	
52  		return empty;			
53  	}
54  	
55  	/**
56  	 * Clear the string buffer.
57  	 */
58  	public void clear() {
59  		buffer.delete(0, buffer.length());
60  	}
61  	
62  }