转自:
下文讲述java.io包中其它字符流的操作实现类,如PushbackReader,LineNumberReader,StreamTokenizer,PrintWriter,StringReader,StringWriter如下所示:
PushbackReader同PushbackInputStream功能非常相似,其不同之处在于PushbackReader处理字符而PushbackInputStream处理字节
PushbackReader reader = new PushbackReader(new FileReader("e:\\test\\input.txt")); /* *设置缓冲区大小的写法 * PushbackReader reader = new PushbackReader(new FileReader("e:\\test\\input.txt"), 8); */ int data = reader.read(); reader.unread(data);
LineNumberReader的功能:用于记录已读取数据行号的BufferedReader
默认情况下,行号从0开始
当LineNumberReader读取到行终止符时
行号会递增
我们可以使用getLineNumber()方法获取当前行号
使用setLineNumber()方法设置当前行数
如下:
LineNumberReader reader = new LineNumberReader(new FileReader("e:\\test\\input.txt")); int data = reader.read(); while(data != -1){ char dataChar = (char) data; data = reader.read(); int lineNumber = reader.getLineNumber(); }
StreamTokenizer可以将输入流转换成一系列符号
然后循环调用nextToken()可以遍历底层输入流的所有符号
每次调用nextToken()之后,StreamTokenizer有一些变量可以帮助我们获取读取到的符号的类型和值
这些变量是:
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader("Mary had 1 little lamb...")); while(tokenizer.nextToken() != StreamTokenizer.TT_EOF){ if(tokenizer.ttype == StreamTokenizer.TT_WORD) { System.out.println(tokenizer.sval); } else if(tokenizer.ttype == StreamTokenizer.TT_NUMBER) { System.out.println(tokenizer.nval); } else if(tokenizer.ttype == StreamTokenizer.TT_EOL) { System.out.println(); } } /* * TT_EOF表示流末尾 * TT_EOL表示行末尾 */
PrintWriter的功能:
将格式化后的数据写入到底层writer中
StringReader的功能:
将原始字符串转换成Reader,如下所示:
Reader reader = new StringReader("输入字符串"); int data = reader.read(); while(data != -1) { //do something with data... doSomethingWithData(data); data = reader.read(); } reader.close();
StringWriter的功能:采用字符串的形式从Writer中获取写入到其中数据,如下所示:
StringWriter writer = new StringWriter(); //write characters to writer. String data = writer.toString(); StringBuffer dataBuffer = writer.getBuffer();