KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > kawa > standard > read_line


1 package kawa.standard;
2 import gnu.lists.FString;
3 import gnu.text.LineBufferedReader;
4 import gnu.mapping.*;
5
6 public class read_line
7 {
8   public static Object JavaDoc apply(LineBufferedReader in, String JavaDoc handling)
9     throws java.io.IOException JavaDoc
10   {
11     int ch = in.read();
12     if (ch < 0)
13       return gnu.expr.Special.eof;
14     int start = in.pos - 1;
15     int pos = start;
16     int limit = in.limit;
17     char[] buffer = in.buffer;
18     int delim = -1; // Length of delimiter.
19

20     // First do a quick scan of what is in in's input buffer.
21
while (pos < limit)
22       {
23         ch = buffer[pos++];
24         if (ch == '\r' || ch == '\n')
25           {
26             pos--;
27             if (handling == "trim" || handling == "peek")
28               {
29                 if (handling == "peek")
30                   delim = 0;
31                 if (ch == '\n')
32                   delim = 1;
33                 else if (pos+1 < limit)
34                   delim = buffer[pos+1] == '\n' ? 2 : 1;
35                 else
36                   break;
37                 in.pos = pos + delim;
38               }
39             else if (handling == "concat" && ch == '\n')
40               {
41                 in.pos = ++pos;
42               }
43             else
44               break;
45             return new FString(buffer, start, pos - start);
46           }
47       }
48
49     // Ok, we haven't found the end-of-line yet, so use the general
50
// readLine method in LineBufferedReader.
51
StringBuffer JavaDoc sbuf = new StringBuffer JavaDoc(100);
52     if (pos > start)
53       sbuf.append(buffer, start, pos - start);
54     in.pos = pos;
55     char mode = handling == "peek" ? 'P'
56       : handling == "concat" || handling == "split" ? 'A'
57       : 'I';
58     in.readLine(sbuf, mode);
59     int length = sbuf.length();
60     if (handling == "split")
61       {
62         if (length == 0)
63           delim = 0;
64         else
65           {
66             char last = sbuf.charAt(length - 1);
67             if (last == '\r')
68               delim = 1;
69             else if (last != '\n')
70               delim = 0;
71             else if (last > 2 && sbuf.charAt(length-2) == '\r')
72               delim = 2;
73             else
74               delim = 1;
75             length -= delim;
76           }
77       }
78     FString dataStr = new FString(sbuf, 0, length);
79     if (handling == "split")
80       {
81         FString delimStr = new FString(sbuf, length-delim, delim);
82         Object JavaDoc[] values = { dataStr, delimStr };
83         return new Values(values);
84       }
85     else
86       return dataStr;
87   }
88 }
89
Popular Tags