1、PipedStream管道流
package com.j2se.io;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* 学习管道流
* @author Administrator
*
*/
public class PipedStreamDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
PipedInputStream pis=new PipedInputStream();
PipedOutputStream pos=new PipedOutputStream();
pis.connect(pos);//管道输入流和管道输出流对接
new Thread(new WritePiped(pos)).start();
new Thread(new ReadPiped(pis)).start();
}
}
class WritePiped implements Runnable{
private PipedOutputStream pos=null;
public WritePiped(PipedOutputStream pos) {
this.pos=pos;
}
@Override
public void run() {
try{
pos.write("Hello PipedOutStream le !!".getBytes());
pos.close();
}catch (Exception e) {
// TODO: handle exception
throw new RuntimeException("输出管道流出错");
}
}
}
class ReadPiped implements Runnable{
private PipedInputStream pis=null;
public ReadPiped(PipedInputStream pis){
this.pis=pis;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
byte[] buffer=new byte[1024];
int len= pis.read(buffer);
String result=new String(buffer, 0, len);
System.out.println("result="+result);
pis.close();
}catch (Exception e) {
// TODO: handle exception
throw new RuntimeException("读取管道流出错。。。");
}
}
}
2、RandomAcessFile:
package com.j2se.io;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* 该类不是IO体系中的子类
* 而是直接继承自object
* RandomAccessFile包装了io流的读写操作,根据指定的模式进行读写
* 内部封装了一个数组,而且通过指针对数组的元素进行操作
* 可以通过getFilePointer获取指针位置
* 如果模式为r,侧不会创建文件,会去读取一个已存在的文件
*
* @author Administrator
*
*/
public class RandomAcessFileDemo {
/**
* 随机访问文件类的学习
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//write_1();
read_1();
}
public static void read_1() throws IOException {
// TODO Auto-generated method stub
RandomAccessFile raf=new RandomAccessFile("src/raf.txt", "r");
byte buffer[]=new byte[4];
raf.read(buffer);
String s=new String(buffer);
int age=raf.readInt();
System.out.println("name:"+s);
System.out.println("age:"+age);
raf.close();
}
public static void write_1() throws IOException{
RandomAccessFile raf=new RandomAccessFile("src/raf.txt", "rw");
raf.write("李四".getBytes());
raf.writeInt(18);
raf.close();
}
}