直接插在文件上,读写文件数据
创建对象
new FileOutputStream(文件)
不管文件是否存在,都会信件一个空文件
new FileOutputStream(文件,true)
文件存在,追加数据
高级流、操作流
与其他流对接,提供特点的数据处理功能
对高级流的操作,会对详解的流执行相同操作
FileOutputStream
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1OutputStream {
public static void main(String[] args) throws IOException {
FileOutputStream out = new FileOutputStream("f3");
out.write(97);//00 00 00 61->61
out.write(98);//00 00 00 62->62
out.write(99);//00 00 00 63->63
out.write(356);//00 00 01 64->64
byte[] a={
101,102,103,104,105,
106,107,108,109,110
};
out.write(a);
out.write(a, 2, 4);
out.flush();
out.close();
System.out.println("写入完成");
}
}
运行结果
写入完成
FileInputStream
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
public class Test2InputStream {
public static void main(String[] args) throws IOException {
FileInputStream in = new FileInputStream("f3");
//单字节读取 5个一批
readByte(in);
in.close();
//流只能顺序读取一次
in = new FileInputStream("f3");
//批量读取
readMore(in);
in.close();
}
private static void readMore(FileInputStream in) throws IOException {
byte[] buff=new byte[5];
int n;
while((n=in.read(buff))!=-1)
{
System.out.println(n+" "+Arrays.toString(buff));
}
System.out.println();
}
private static void readByte(FileInputStream in) throws IOException {
int b;
while((b=in.read())!=-1)
{
System.out.print(b+" ");
}
System.out.println();
}
}
运行结果
97 98 99 100 101 102 103 104 105 106 107 108 109 110 103 104 105 106
5 [97, 98, 99, 100, 101]
5 [102, 103, 104, 105, 106]
5 [107, 108, 109, 110, 103]
3 [104, 105, 106, 110, 103]