IO流体系庞大,根据方向分为:输入流、输出流
根据对象分为:字节流、字符流
FileInputStream与FileOutputStream
这两个流,比较常见。用于文件的读写操作。同时他们继承与抽象类InputStream和OutputStream。
文件读到程序中
1、每次读取一个字节
/**读取一个文件,以十六进制打印出来*/
public static void printHex(String filename) throws IOException {
int b;
int i =1;
FileInputStream inputStream = new FileInputStream(filename); //创建输入流对象
while ((b=inputStream.read())!= -1){ //一次读取一个字节,读到-1结束
System.out.print(Integer.toHexString(b)+ " ");
/*if (i++%2 == 0) //每行打印两个
System.out.println();*/
}
inputStream.close();
}
2、读取到数组缓冲区
public static void printHexByBuf(String filename) throws IOException{
//1、创建输入文件流
FileInputStream in = new FileInputStream(filename);
//2、定义buf数组,放文件字节
byte[] buf = new byte[1024];
//3.用read方法读到buf中,返回文件的字节个数
int bytes = in.read(buf,0,buf.length);
//4、数组长度是字节的个数
for (int i =0; i<bytes;i++){
System.out.println(buf[i]);
}
}
3、文件拷贝
/**s文件拷贝*/
public static void copyFile(File srcFile ,File desFile) throws IOException{
//1、判断源文件是否存在
if (!srcFile.exists()){
throw new IllegalArgumentException("文件"+ srcFile + "不存在");
}
//2、判断源文件是文件吗,目录就不复制
if (!srcFile.isFile()){
throw new IllegalArgumentException(srcFile + "不是文件");
}
//3、创建文件输入流,与输出流对象
FileInputStream in = new FileInputStream(srcFile); //将文件读到程序中
FileOutputStream out = new FileOutputStream(desFile); //程序中的数据写出到文件中
//4、创建字节数组,存放读取的文件
byte[] buf = new byte[1024*6];
int bytes =in.read(buf,0,buf.length); //读到buf缓存中
out.write(buf,0,bytes); //写到文件输出流中
//5、关闭流对象
in.close();
out.close();
}
DataInputStream与DateOutputStream
是对File流的扩展,为了更好的支持多种数据类型的读写
/**
* DataOutputStream/DataInputStream
* 对流功能的扩展,支持更多类型是读写,
* 原来只支持byte类型
* */
//利用DataOutputStream类,写文件
public static void writeDataToFile(String filename) throws IOException{
//1、创建数据输出流
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename)); /**需要File对象*/
//2.利用DataOutputStream对象的write()实现向文件写多种数据类型
out.writeInt(10);
out.writeLong(10L);
out.writeDouble(34.5);
out.writeUTF("中国");
out.close();
out.close();
IoUtils.printHex(filename);
}
字节缓冲流
BufferedInputStream \ BufferedOutputStream (带缓冲的字节流)为IO提供带缓冲区的实现,提高了IO性能