字符串流
以一个字符串为数据源,来构造一个字符流
作用:
在WEB开发中,我们经常要从服务器上获取数据,数据的返回格式通过是一个字符串(xml,json),我们需要把这个字符串构造成一个字符流,然后再用第三方的数据解析器来解析数据。
StringReader
其源为一个字符串的字符流
StringWriter
一个字符流,可以用其回收在字符串缓冲区中的输出类构造字符串。关闭StringWriter无效。此类中的方法在关闭该流后仍可被调用,而不会产生任何IOException。
代码示例:
计算英文语句单词个数
package com.booy;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
public class StringReaderDemo {
public static void main(String[] args) {
stringReader();
}
private static void stringReader() {
String info = "good good study,day day up!";
StringReader sr = new StringReader(info);
//流标记器
StreamTokenizer st = new StreamTokenizer(sr);
int count = 0;
//流标记类型不等于最后 开始执行
while(st.ttype!= StreamTokenizer.TT_EOF) {
try {
if(st.nextToken()==StreamTokenizer.TT_WORD) {
count++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
sr.close();
System.out.println("单词的个数是:"+count+"个");
}
}
管道流
管道输入流应该连接到管道输出流;管道输入流提供要写入管道输出流的所有数组字节。通常,数据由某个线程从PipedInputStream对象读取,并由其他线程将其写入到相应的PipedOutputStream。不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。管道输入流包含一个缓冲区,可以在缓冲区限定的范围内将读操作和写操作分离开。如果向连接管道输出流提供数据字节的线程不再存在,则认为该管道已损坏。
代码示例:
package com.booy;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
//管道流
public class PipedStreamDemo {
public static void main(String[] args) {
PipedInputStream pin = new PipedInputStream();
PipedOutputStream pout = new PipedOutputStream();
try {
pin.connect(pout);//输入流与输出流连接
} catch (IOException e) {
e.printStackTrace();
}
ReadThread rt =new ReadThread(pin);
WriteThread wt = new WriteThread(pout);
new Thread(rt).start();
new Thread(wt).start();
}
}
class ReadThread implements Runnable{
private PipedInputStream pin; //输入管道
public ReadThread(PipedInputStream pin) {
this.pin = pin;
}
public void run() {
byte[] bytes = new byte[1024];
try {
int len = pin.read(bytes);//read阻塞
String s = new String(bytes,0,len);
System.out.println("管道爬出一个"+s);
pin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class WriteThread implements Runnable{
private PipedOutputStream pout; //输出管道
public WriteThread(PipedOutputStream pout) {
this.pout = pout;
}
public void run() {
try {
pout.write("午夜凶铃".getBytes());
pout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}