KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > python > modules > cStringIO


1 /*
2  * Copyright 1998 Finn Bock.
3  *
4  * This program contains material copyrighted by:
5  * Copyright (c) 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
6  * The Netherlands.
7  */

8
9 package org.python.modules;
10
11 import java.io.*;
12 import java.util.*;
13
14 import org.python.core.*;
15
16 /**
17  * This module implements a file-like class, StringIO, that reads and
18  * writes a string buffer (also known as memory files).
19  * See the description on file objects for operations.
20  * @author Finn Bock, bckfnn@pipmail.dknet.dk
21  * @version cStringIO.java,v 1.10 1999/05/20 18:03:20 fb Exp
22  */

23 public class cStringIO {
24     /**
25      * Create an empty StringIO object
26      * @return a new StringIO object.
27      */

28     public static StringIO StringIO() {
29         return new StringIO();
30     }
31
32     /**
33      * Create a StringIO object, initialized by the value.
34      * @param buf The initial value.
35      * @return a new StringIO object.
36      */

37     public static StringIO StringIO(String JavaDoc buf) {
38         return new StringIO(buf);
39     }
40
41
42     /**
43      * The StringIO object
44      * @see cStringIO#StringIO()
45      * @see cStringIO#StringIO(String)
46      */

47     public static class StringIO extends PyObject {
48         transient public boolean softspace = false;
49         transient public String JavaDoc name = "<cStringIO>";
50         transient public String JavaDoc mode = "w";
51         transient public boolean closed = false;
52
53         transient private char[] buf;
54         transient private int count;
55         transient private int pos;
56
57
58         StringIO() {
59             this.buf = new char[16];
60         }
61
62
63         StringIO(String JavaDoc buf) {
64             this.buf = new char[buf.length() + 16];
65             write(buf);
66             seek(0);
67         }
68
69
70         public void __setattr__(String JavaDoc name, PyObject value) {
71             if (name == "softspace") {
72                 softspace = value.__nonzero__();
73                 return;
74             }
75             super.__setattr__(name, value);
76         }
77
78         public PyObject __iter__() {
79             return new PyCallIter(__getattr__("readline"), Py.newString(""));
80         }
81
82         /**
83          * Free the memory buffer.
84          */

85         public void close() {
86             buf = null;
87             closed = true;
88         }
89
90
91         /**
92          * Return false.
93          * @return false.
94          */

95         public boolean isatty() {
96             return false;
97         }
98
99
100         /**
101          * Position the file pointer to the absolute position.
102          * @param pos the position in the file.
103          */

104         public void seek(long pos) {
105             seek(pos, 0);
106         }
107
108
109         /**
110          * Position the file pointer to the position in the .
111          * @param pos the position in the file.
112          * @param mode; 0=from the start, 1=relative, 2=from the end.
113          */

114         public void seek(long pos, int mode) {
115             if (mode == 1)
116                 this.pos = (int)pos + this.pos;
117             else if (mode == 2)
118                 this.pos = (int)pos + count;
119             this.pos = Math.max(0, (int)pos);
120         }
121
122         /**
123          * Reset the file position to the beginning of the file.
124          */

125         public void reset() {
126             pos = 0;
127         }
128
129         /**
130          * Return the file position.
131          * @returns the position in the file.
132          */

133         public long tell() {
134             return pos;
135         }
136
137
138
139         /**
140          * Read all data until EOF is reached.
141          * An empty string is returned when EOF is encountered immediately.
142          * @returns A string containing the data.
143          */

144         public String JavaDoc read() {
145             return read(-1);
146         }
147
148
149         /**
150          * Read at most size bytes from the file (less if the read hits EOF).
151          * If the size argument is negative, read all data until EOF is
152          * reached. An empty string is returned when EOF is encountered
153          * immediately.
154          * @param size the number of characters to read.
155          * @returns A string containing the data read.
156          */

157         public String JavaDoc read(int size) {
158             opencheck();
159             int newpos = (size < 0) ? count : Math.min(pos+size, count);
160             String JavaDoc r = null;
161             if (size == 1 && newpos > pos) {
162                 r = cStringIO.getString(buf[pos]);
163             } else {
164                 r = new String JavaDoc(buf, pos, newpos-pos);
165             }
166             pos = newpos;
167             return r;
168         }
169
170
171         private int indexOf(char ch, int pos) {
172             for (int i = pos; i < count; i++) {
173                 if (buf[i] == ch)
174                     return i;
175             }
176             return -1;
177         }
178
179
180         /**
181          * Read one entire line from the file. A trailing newline character
182          * is kept in the string (but may be absent when a file ends with
183          * an incomplete line).
184          * An empty string is returned when EOF is hit immediately.
185          * @returns data from the file up to and including the newline.
186          */

187         public String JavaDoc readline() {
188             return readline(-1);
189         }
190
191
192         /**
193          * Read one entire line from the file. A trailing newline character
194          * is kept in the string (but may be absent when a file ends with an
195          * incomplete line).
196          * If the size argument is non-negative, it is a maximum byte count
197          * (including the trailing newline) and an incomplete line may be
198          * returned.
199          * @returns data from the file up to and including the newline.
200          */

201         public String JavaDoc readline(int length) {
202             opencheck();
203             int i = indexOf('\n', pos);
204             int newpos = (i < 0) ? count : i+1;
205             if (length != -1 && pos + length < newpos)
206                 newpos = pos + length;
207             String JavaDoc r = new String JavaDoc(buf, pos, newpos-pos);
208             pos = newpos;
209             return r;
210         }
211
212
213         /**
214          * Read and return a line without the trailing newling.
215          * Usind by cPickle as an optimization.
216          */

217         public String JavaDoc readlineNoNl() {
218             int i = indexOf('\n', pos);
219             int newpos = (i < 0) ? count : i;
220             String JavaDoc r = new String JavaDoc(buf, pos, newpos-pos);
221             pos = newpos;
222             if (pos < count) // Skip the newline
223
pos++;
224             return r;
225         }
226
227
228
229         /**
230          * Read until EOF using readline() and return a list containing
231          * the lines thus read.
232          * @return a list of the lines.
233          */

234         public PyObject readlines() {
235             return readlines(0);
236         }
237
238
239         /**
240          * Read until EOF using readline() and return a list containing
241          * the lines thus read.
242          * @return a list of the lines.
243          */

244         public PyObject readlines(int sizehint) {
245             opencheck();
246             int total = 0;
247             PyList lines = new PyList();
248             String JavaDoc line = readline();
249             while (line.length() > 0) {
250                 lines.append(new PyString(line));
251                 total += line.length();
252                 if (0 < sizehint && sizehint <= total)
253                     break;
254                 line = readline();
255             }
256             return lines;
257         }
258
259         /**
260          * truncate the file at the current position.
261          */

262         public void truncate() {
263             truncate(-1);
264         }
265
266         /**
267          * truncate the file at the position pos.
268          */

269         public void truncate(int pos) {
270             opencheck();
271             if (pos < 0)
272                 pos = this.pos;
273             if (count > pos)
274                 count = pos;
275         }
276
277
278         private void expandCapacity(int newLength) {
279             int newCapacity = (buf.length + 1) * 2;
280             if (newLength > newCapacity) {
281                 newCapacity = newLength;
282             }
283
284             char newBuf[] = new char[newCapacity];
285             System.arraycopy(buf, 0, newBuf, 0, count);
286             buf = newBuf;
287             //System.out.println("newleng:" + newCapacity);
288
}
289
290
291         /**
292          * Write a string to the file.
293          * @param s The data to write.
294          */

295         public void write(String JavaDoc s) {
296             opencheck();
297             int newpos = pos + s.length();
298
299             if (newpos >= buf.length)
300                 expandCapacity(newpos);
301             if (newpos > count)
302                 count = newpos;
303
304             s.getChars(0, s.length(), buf, pos);
305             pos = newpos;
306         }
307
308
309         /**
310          * Write a char to the file. Used by cPickle as an optimization.
311          * @param ch The data to write.
312          */

313         public void writeChar(char ch) {
314             if (pos+1 >= buf.length)
315                 expandCapacity(pos+1);
316             buf[pos++] = ch;
317             if (pos > count)
318                 count = pos;
319         }
320
321
322         /**
323          * Write a list of strings to the file.
324          */

325         public void writelines(String JavaDoc[] lines) {
326             for (int i = 0; i < lines.length; i++) {
327                 write(lines[i]);
328             }
329         }
330
331
332         /**
333          * Flush the internal buffer. Does nothing.
334          */

335         public void flush() {
336             opencheck();
337         }
338
339
340         /**
341          * Retrieve the entire contents of the ``file'' at any time
342          * before the StringIO object's close() method is called.
343          * @return the contents of the StringIO.
344          */

345         public String JavaDoc getvalue() {
346             opencheck();
347             return new String JavaDoc(buf, 0, count);
348         }
349
350
351         private final void opencheck() {
352             if (buf == null)
353                 throw Py.ValueError("I/O operation on closed file");
354         }
355     }
356
357
358     private static String JavaDoc[] strings = new String JavaDoc[256];
359     static String JavaDoc getString(char ch) {
360         if ((int)ch > 255) {
361             return new String JavaDoc(new char[] { ch });
362         }
363
364       String JavaDoc s = strings[(int)ch];
365
366       if (s == null) {
367           s = new String JavaDoc(new char[] { ch });
368           strings[(int)ch] = s;
369       }
370       return s;
371    }
372 }
373
Popular Tags