管道流---多线程和IO结合
PipedInputStream
PipedOutputStream
管道输入流应该连接到管道输出流;
管道输入流提供要写入管道输出流的所有数据字节。
通常,数据由某个线程从 PipedInputStream 对象读取,
并由其他线程将其写入到相应的 PipedOutputStream。
不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。
*/
import java.io.*;
class Read implements Runnable
{
private PipedInputStream in;
Read(PipedInputStream in)
{
this.in=in;
}
public void run()
{
try
{
byte[] buf=new byte[1024];
int len=in.read(buf);//阻塞状态
String s=new String(buf,0,len);
system.out.println(s);
in.close();
}
catch (IOException e)
{
throw new RuntimeException("管道读取流失败");
}
}
}
class Write implements Runnable
{
private PipedOutputStream out;
Write(PipedOutputStream out)
{
this.out=out;
}
public void run()
{
try
{
out.write("guandao laile".getBytes());
out.close();
}
catch (IOException e)
{
throw new RuntimeException("管道写入流失败");
}
}
}
class PipedStreamDemo
{
public static void main(String[] args)throws IOException
{
PipedInputStream in=new PipedInputStream();
PipedOutputStream out=new PipedOutputStream();
in.connect(out);
Read r=new Read();
Write w=new Write();
new Thread(r).Start();
new Thread(w).Start();
}
}
------------------------------------
/*
RandomAccessFile
这类不算是IO体系中的子类
而是直接继承自object.
但它是IO包中的成员,因为它具备读和写功能
内部封装了一个大型byte数组,而且通过指针对数组的元素进行操作
可以通过getFilePionter获取指针位置
同时可以通过seek改变指针的位置
其实完成读写的原理是内部封装了字节输入流和输出流
通过构造函数可以,该类只能操作文件
而且操作文件还有模式只读r 读写rw
如果模式为只读r,就不会创建文件,会去读取一个已存在的文件,如果文件不存在,则会出现异常
如果模式为rw,而且该对象构造函数要操作的文件不存在,会自动创建,如果存在不会覆盖
*/
class RandomAccessFileDemo
{
public static void main(String[] args) throws IOException
{
//writeFile();
writeFile_2();
//readFile();
}
public static void readFile()throws IOException
{
RandomAccessFile raf=new RandomAccessFile("ran.txt","r");
//调整对象中的指针
//raf.seek(8*1);
//跳过指定的字节数,只能往后跳
raf.skipBytes(8);
byte[] buf=new byte[4];
raf.read(buf);
String name=new String(buf);
int age=raf.readInt();
System.out.println("name="+name);
System.out.println("age="+age);
raf.close();
//System.out.print();
}
public static void writeFile_2()throws IOException
{
RandomAccessFile raf=new RandomAccessFile("ran.txt","rw");
raf.seek(8*3);
raf.write("zhaoliu".getBytes());
raf.writeInt(103);
raf.close();
}
public static void writeFile()throws IOException
{
RandomAccessFile raf=new RandomAccessFile("ran.txt","rw");
raf.write("lisi".getBytes());
raf.writeInt(97);
raf.close();
}
}
-----------------------------------
import java.io.*;
class Person implements Serializable//标识接口,可以实例化
{
public static final long serialVersionUID = 42L;
String name;
int age;
static String country="cn";//加静态和transient,不可实例化
Person(String name,int age)
{
this.name=name;
this.age=age;
this.country=country;
}
public String toString()
{
return name+":"+age+country;
}
}