/**
* 字符串流:以一個(gè)字符串為數(shù)據(jù)源度硝,來(lái)構(gòu)造一個(gè)字符流
* 作用:在web開(kāi)發(fā)中,經(jīng)常要從和服務(wù)器上獲取數(shù)據(jù),數(shù)據(jù)的返回格式通常是一個(gè)字符串(xml,json)想罕,我們需要把這個(gè)字符串構(gòu)造成一個(gè)字符流
* 然后再用第三方的數(shù)據(jù)解析器來(lái)解析數(shù)據(jù)秘蛇。
*/
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.io.StringWriter;
public class StringStreamDemo {
public static void main(String[] args) {
stringReadr();
stringWriter();
}
public static void stringReadr() {
String info = "good good study day day up";
StringReader sr = new StringReader(info);
//流標(biāo)記器
StreamTokenizer st = new StreamTokenizer(sr);
int count = 0;
while(st.ttype!=StreamTokenizer.TT_EOF) { //ttype表示流標(biāo)記器里的某一個(gè)類(lèi)型耳璧;TT_EOF表示某一個(gè)類(lèi)型的結(jié)束的標(biāo)記位置
try {
if(st.nextToken()==StreamTokenizer.TT_WORD) { //判斷流標(biāo)記器的下一個(gè)類(lèi)型是否等于流標(biāo)記器里的單詞盗忱;TT_WORD表示類(lèi)型是單詞
count++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
sr.close();
System.out.println("count="+count);
}
public static void stringWriter() {
StringWriter sw = new StringWriter();
sw.write("this is StringWriter test...");
String info = sw.toString();
System.out.println(info);
}
}
管道流
管道流:
管道輸入流應(yīng)該連接到管道輸出流治筒;管道輸入流提供要寫(xiě)入管道輸出流的所有數(shù)據(jù)字節(jié)屉栓。通常,數(shù)據(jù)由某個(gè)線程從PipedInputStream對(duì)象讀取耸袜,并由其他線程將其寫(xiě)入到相應(yīng)的PipedOutputStream友多,不建議對(duì)這兩個(gè)對(duì)象嘗試使用單個(gè)線程,因?yàn)?這樣可能死鎖線程堤框。管道輸入流包含一個(gè)緩沖區(qū)域滥,可在緩沖區(qū)限定的范圍內(nèi)將讀操作和寫(xiě)操作分離開(kāi)。如果想連接管道輸出流提
供數(shù)據(jù)字節(jié)的線程不再存在蜈抓,則認(rèn)為該管道已損壞启绰。
/**
* 管道流:一個(gè)線程寫(xiě)入,一個(gè)線程讀取
* 作用资昧,用于線程之間的數(shù)據(jù)通訊
*
*/
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); //兩個(gè)管道進(jìn)行連接酬土,輸入管道連接輸出管道
} catch (IOException e) {
e.printStackTrace();
}
ReadThread readTh = new ReadThread(pin);
WriteThread writeTh = new WriteThread(pout);
new Thread(readTh).start(); //啟動(dòng)線程,要先啟動(dòng)讀入的線程格带;
new Thread(writeTh).start(); //再啟動(dòng)寫(xiě)入的線程
}
}
//讀取數(shù)據(jù)的線程
class ReadThread implements Runnable {
private PipedInputStream pin; //輸入管道
ReadThread(PipedInputStream pin){
this.pin=pin;
}
public void run() {
byte[] buf = new byte[1024];
int len;
try {
len = pin.read(buf); //read阻塞
String s = new String(buf,0,len);
System.out.println("讀到:"+s);
pin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//寫(xiě)入數(shù)據(jù)的線程
class WriteThread implements Runnable{
private PipedOutputStream pout; //輸出管道
public WriteThread(PipedOutputStream pout){
this.pout=pout;
}
public void run() {
try {
pout.write("一個(gè)美女...".getBytes()); //管道輸出流
pout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者