打印流:
这个流的主要作用就是打印文字,它的目标主要是文件,屏幕,网络。打印流属于输出流。它分为PrintStream,PrintWriter
PrintStream中的Print方法就是键盘录入,PrintStream中的Writer方法就是打印的是二进制的后四位。
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
public class IoDemo{
public static void main(String[] args) throws IOException {
PrintStream ps=new PrintStream("e:/lishuai.txt");
ps.print(78);
ps.print("lishuai");
ps.println();
ps.write(85);
}
}
PrintWriter字符输出流的打印流,当在创建对象的时候,根据api中介绍的构造方法能够开启了自动刷新的功能,当我们使用PrintWriter中的printf、println、format方法写出数据的时候,就会自动刷新。
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class IoDemo{
public static void main(String[] args) throws IOException {
PrintWriter pw=new PrintWriter(new FileWriter("e:/lishuai.txt",true));
pw.println("lishualiu");
}
}
###管道流:
这个流的特点是可以把输入和输出流直接对接起来,我们不用在两个之间定义任何的变量或者数组。PipedInputStream和PipedOutputStream 字节输入和输出的管道流PipedReader和PipedWriter字符输入和输出的管道流管道输入流它是负责从管道读取数据,管道输出流它负责把数据写到管道中。
```java
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class IoDemo {
public static void main(String[] args) throws IOException {
PipedInputStream pi = new PipedInputStream();
PipedOutputStream po = new PipedOutputStream();
pi.connect(po);
Input in=new Input(pi);
Output ou=new Output(po);
Thread t1=new Thread(in);
Thread t2=new Thread(ou);
t1.start();
t2.start();
}
}
class Input implements Runnable {
PipedInputStream pi;
Input(PipedInputStream pi) {
this.pi = pi;
}
@Override
public void run() {
// TODO Auto-generated method stub
int len = 0;
byte[] b = new byte[1024];
try {
while ((len = pi.read(b)) != -1) {
System.out.println(new String(b, 0, len));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
pi.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Output implements Runnable {
PipedOutputStream po;
Output(PipedOutputStream po) {
this.po = po;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
po.write("李帅的输出".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
po.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}