## IO流的输入和输出
子节流:
工具类:
package IO;
import java.io.*;
public class IOUtil {
/*
读取指定文件内容,按照16进制输出到控制台
每输出10个byte换行
*/
public static void printHex(String filename)throws IOException {
//把文件作为字节流进行读操作
FileInputStream in = new FileInputStream(filename);
int b;
int i=1;
while ((b=in.read())!=-1){
if(b<=0xf){
//单位数面前补0
System.out.println("0");
}
System.out.println(Integer.toHexString(b)+" ");//将整形b转换成16进制进行打印
if(i++%10==0){
System.out.println();
}
}
//千万不要忘了关闭
in.close();
}
/*
读取指定文件内容,按照16进制输出到控制台
每输出10个byte换行
*/
public static void printHexBYByteArr(String filename)throws IOException {
//把文件作为字节流进行读操作
FileInputStream in = new FileInputStream(filename);
byte[] buf=new byte[20*1024];
/*从in中批量读取字节,放入到buf这个字节数组中,从第0个位置开始放,最多放buf.length个
返回的是读到的字节的个数
*/
//这个方式好,节省了内存空间
int bytes = 0;
int j = 1;//计数
while ((bytes=in.read(buf,0,buf.length))!=-1){
for(int i =0;i<bytes;i++){
System.out.print(Integer.toHexString(buf[i]&0xff)+" ");
if(j++%10==0){
System.out.println();
}
}
}
in.close();
}
/*
写的操作
实现一个文件的拷贝操作
File srcFile目标文件
File destFile 拷贝到哪个文件
*/
public static void copyFile(File srcFile,File destFile)throws IOException{
if(!srcFile.exists()){
throw new IllegalArgumentException("目标文件不存在");
}
if(!srcFile.isFile()){
throw new IllegalArgumentException("不是文件");
}
//开始进行读写操作
//读
FileInputStream in = new FileInputStream(srcFile);
//写
FileOutputStream out =new FileOutputStream(destFile);//此处没有加true参数,则destFile文件不存在时会自动创建
byte[] buf = new byte[10*1024];
int b ;
while ((b=in.read(buf,0,buf.length))!=-1){
out.write(buf,0,b);
out.flush();
}
in.close();
out.close();
}
/*
写的操作
实现一个文件的拷贝操作(利用带缓冲的字节流)
File srcFile目标文件
File destFile 拷贝到哪个文件
*/
public static void copyFilebyBuffer(File srcFile,File destFile)throws IOException{
if(!srcFile.exists()){
throw new IllegalArgumentException("目标文件不存在");
}
if(!srcFile.isFile()){
throw new IllegalArgumentException("不是文件");
}
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos =new BufferedOutputStream(new FileOutputStream(destFile));
int c;
while((c=bis.read())!=-1){
bos.write(c);
bos.flush();
}
bis.close();
bos.close();
}
}
测试类:
package IO;
import java.io.File;
import java.io.IOException;
public class IOUtilTest1 {
public static void main(String[] args){
try {
// IOUtil.printHex("F:\\idea\\imooc\\demo\\raf.txt");
// IOUtil.printHexBYByteArr("F:\\idea\\imooc\\demo\\raf.txt");
// IOUtil.copyFile(new File("F:\\idea\\imooc\\demo\\raf.txt"),new File("F:\\idea\\imooc\\demo\\raf2.txt"));
IOUtil.copyFilebyBuffer(new File("F:\\idea\\imooc\\demo\\raf.txt"),new File("F:\\idea\\imooc\\demo\\raf3.txt"));
} catch (IOException e) {
e.printStackTrace();
}
}
}