java流式输入/输出原理
java流类的分类
输入/输出流类
常见的节点流和处理流
文件流
缓冲流
数据流
转换流
Print流
Object流
1 流(程序输入或输出数据的标准方法(把0101的输出外加一层其他的))
1)按数据流方向不同分为输入流 输出流
2)按处理数据单位不同分为字节流 字符流(1字符=两字节)
3)按功能不同分为节点流(改变原有方法) 处理流(在原有方法上添加方法)
2 四种抽象流类型
3 按数据流方向不同分为输入流 输出流
按处理数据单位不同分为字节流 字符流
按功能不同分为节点流(改变原有方法) 处理流(在原有方法上添加方法)
1)套管道
FileOutputStream fos = new FileOutputStream("d:/share/java/io/testobjectio.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
2)以此为例
InputStream
int read() throws IOException
//读取一个字节并以整数的形式返回(0--255)
//若返回-1已到输入流末尾
int read(byte[] buffer) throws IOException
//读取一系列字节并存储到一个数组buffer(减少读取硬盘次数)
//返回实际读取的字节数,若读取到末尾返回1
int read(byte[] buffer, int offset, int length)throws IOException
//读取length个字节
//并存储到一个字节数组buffer,从offset开始
//同上
void close() throws IOException
//关闭释放内存资源
long skip(long n) throws IOException
//跳过n个字节不读,返回实际跳过字节数
深色为节点,浅色为字符
4)OutStream个例
1)改为write
2)a.flush();//将输出流中缓冲的数据全部写出到目的地
5)缓冲流
把file改为buffered(13转换为char为换行符)
1)b.newLine();//写一个换行符
2)b.mark(100);//在第100个做标记,从第100个开始
3)b.reset();//回到标记位置
4)String s = b.readLine();//读一行
6)转换流
osw.getEncoding();//获取编码,默认gbk
OutputStreaWriter osw = new OutputStreamWriter(new FileOutputStream("g:\\java\\s.txt"));
OutputStreaWriter osw = new OutputStreamWriter(new FileOutputStream("g:\\java\\s.txt",true),"IS08859_1");//true从原有内容添加(可用于做日志),指定编码
InputStreamReader isr =
new InputStreamReader(System.in);//按字节读取不便,包一层InputStreamReader(System.in同步/堵塞,不输入程序不继续)
7) 数据流(DateInputStream/DateOutputStream)
import java.io.*;
public class TestDataStream {
public static void main(String[] args) {
ByteArrayOutputStream baos =
new ByteArrayOutputStream(); //产生字节数组内存,及处理方法
DataOutputStream dos =
new DataOutputStream(baos);//方法外套方法
try {
dos.writeDouble(Math.random());//写入8字节随机数
dos.writeBoolean(true);//写入1字节
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());//读取
System.out.println(bais.available());//打印字节数
DataInputStream dis = new DataInputStream(bais);
System.out.println(dis.readDouble());//先写的先读,否则会读出先写内容的部分内容(先进先出)
System.out.println(dis.readBoolean());
dos.close(); dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
8)Print流
不会抛出异常
import java.io.*;
public class TestPrintStream1 {
public static void main(String[] args) {
PrintStream ps = null;
try {
FileOutputStream fos =
new FileOutputStream("d:\\bak\\log.dat");//管道
ps = new PrintStream(fos);//套管道(其他类型也是如此)
} catch (IOException e) {
e.printStackTrace();
}
if(ps != null){
System.setOut(ps);//改变out指向ps,所以打印内容在文件内
}
int ln = 0;
for(char c = 0; c <= 60000; c++){
System.out.print(c+ " ");
if(ln++ >=100){ System.out.println(); ln = 0;}
}
}
}
9)Object流(ObjectOutputStream/OutInputStream)
Serializable接口
class T
implements Serializable//要想把某类序列化,必须实现此接口
{
int i = 10;
int j = 9;
double d = 2.3;
transient int k = 15;//透明的,序列化时不予考虑,读时为0
}
externalizable接口(控制序列化过程)