其他流的使用
标准的输入输出流
- System.in:标准的输入流,默认从键盘输入
- System.out:标准的输出流,默认从控制台输出
可以通过System的setIn(InputStream)和setOut(PrintfStream)来重写指定输入输出的流
打印流
printStream
- 可以setOut()替换Sys.out这个打印流
PrintWriter
数据流
DataInputStream和DataOutputStream
- radeBoloean()
- readByte()等
读取或写出基本数据类型的字符串,字节流套在里面
对象流
ObjectInputStream和ObjectOutputStream
- 用于存储和读取基本数据类型和对象的处理流,可以序列化和反序列化对象
- 序列化:保存对象
- 反序列化,读取对象到内存
不能序列化Stataic和transient
自定义类的序列化
实现sarializable
- 实现externalizable
- 提供一个public static final long sarialVersinUid
- 自定义对象的属性也必须是可序列化的(String,基本数据类型)
static和transient不可序列化
//对象流
ObjectOutputStream out = null;
ObjectInputStream in = null;
try {
FileOutputStream fileOut = new FileOutputStream("object.txt");
out = new ObjectOutputStream(fileOut);
out.writeObject(new String("对象流测试"));
out.flush();
FileInputStream fileIn = new FileInputStream("object.txt");
in = new ObjectInputStream(fileIn);
String result = (String)in.readObject();
System.out.println(result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(in != null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
随机存取文件流
RandomAccessFile
- 实现了DataOutput和DataInput接口,即可以读,也可以写
seek(pointer)设定指针
扩展
ByteArrayOutputStream
write()不输出,最后toString()获取结果;Java NIO
1.4引入的一套IO API,可以替代标准的Java IO API,NIO是面向缓冲区buffer的(区别于流),基于通道channel的IO操作。
- 有两套NIO,一套是标准输入输出NIO,另一套是网络编程NIO.
- java.nio.channels.channel
Filechannel 处理本次文件
SocketChannel TCP网络编程的客户端channel
serverSocketChannel 服务器端channel
DatagramChannel UDp网络编程中发送端和接收端的channel - Path、Paths、Files