Java IO流 --- 字节流的操作

1. 读取文件
    1).建立与文件的联系 ---> 通过File对象
    2).选择流 ---> 文件输入流 FileInputStream 从源头输入到程序端
    3).操作 ---> 创建缓存字节数组  byte[] b = new byte[1024] 1024即为一次读取的字节数
     + read  循环读取 while(-1!=(len=(is。read()))) 
     将is。reader()返回的值赋给len 若没有数据is。reader()返回-1结束循环
     每次读取长度为len,若需要读取的数据字节数大于len,则多次读取
    4).释放资源 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * 读取文件
	1.建立与文件的联系 ---> 通过File对象
	2.选择流 ---> 文件输入流 FileInputStream 从源头输入到程序端
	3.操作 ---> 创建缓存字节数组  byte[] b = new byte[1024] 1024即为一次读取的字节数
	 + read  循环读取 while(-1!=(len=(is。read()))) 
	 将is。reader()返回的值赋给len 若没有数据is。reader()返回-1结束循环
	 每次读取长度为len,若需要读取的数据字节数大于len,则多次读取
	4.释放资源 
 * @author Administrator
 *
 */
public class Test01 {
	public static void main(String[] args) {
		//建立与文件的联系
		File src = new File("D:/CER/img/Out.txt");
		//选择流
		InputStream is = null; //在异常捕获操作中将局部变量提升为成员变量,提升变量的作用域
		try {
			 is = new FileInputStream(src);
			 //读取文件
			 byte[] b = new byte[1024];//缓冲数组,后面每次读取字节长度不能大于缓冲数组长度,缓存区满了会覆盖之前的内容?
			 int len = 0; //记录实际读取的大小,一个汉字是两个字节,所以如果定义为1则会乱码  
			 
			 //len与定义缓冲长度有一定关系,具体关系?
			 
			 //循环读取,没有数据时isread()会返回-1(没有数据),循环结束,不等于-1循环读取
			 while(-1!=(len=(is.read(b)))){
				 //输出  将字节数组转为字符串
				 String info = new String(b, 0, len);//字节数组b;从第0个开始;每次输出字节长度为len
				 System.out.print(info);
				 
			 }
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("文件不存在");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("读取文件失败");
		}
		//释放资源
		finally{
			if (null!=is) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println("关闭输入流失败");
				}
			}
		}
	}
}

2.写入文件
    1).建立与文件的联系 ---> 通过File对象
    2).选择流 ---> 文件输出流  FileOutputStream 从程序端输出到目的地
    3).操作 ---> 写入数据(将输入数据(如字符数组)转为字节数组)并刷新   write +flush
    4).释放资源 

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 写入文件
	1.建立与文件的联系 --->通过File对象,寻找数据输入的目的地
	2.选择流 ---> 文件输出流  FileOutputStream 从程序端输出到目的地
	3.操作 ---> 写入数据并刷新   write ---> 将字符串转换为字符数组
	写入数据判定
	添加(true)|覆盖(false,默认) ,
	写入的数据覆盖之前数据,默认为false,若需要在之前数据之后添加数据则需要将判断为设为true
	+flush 强制刷新,清理缓存区数据
	4.释放资源 
 * @author Administrator
 *
 */
public class Test02 {
	public static void main(String[] args) {
		//建立与文件的联系
		File dest = new File("D:/CER/img/In.txt");
		//选择流
		OutputStream os = null;
		
		try {
			//boolean参数表示写入的数据是添加(true)还是覆盖(false,默认)
			os = new FileOutputStream(dest,true);
			//写入操作
			String str = "写入数据 \r\n";
			//字符串转为字节数组
			byte[] data = str.getBytes();
			os.write(data);
			os.flush();//强制刷新
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("未找到文件");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("文件写入失败");
		}finally{
			//释放资源
			if (null!=os) {
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println("关闭输出流失败");
				}
			}
		}
	}
}

3. 文件拷贝
    数据源 ---> 程序 ---> 目的地
    1).建立联系 ---> 通过File对象
    2).选择流   
        文件输入流 FileInputStream 从源头输入到程序端
        文件输出流  FileOutputStream 从程序端输出到目的地
    3).操作  拷贝
        读取 ---> 创建字节数组 byte[] b = new byte[1024] + read + 定义读取大小len
        写入 ---> 将字节数组写入并刷新   write +flush
    4).释放资源 
    

/**
 * 拷贝文件
 * 拷贝文件夹
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream.GetField;
import java.io.OutputStream;

public class FileUtil {
	/**
	 * 
	 * @param scrPath 数据源路径
	 * @param destPath 拷贝目标路径
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void copyFile(String scrPath,String destPath) throws FileNotFoundException,IOException {
		//建立联系
	//	File src = new File(scrPath);//数据源 存在且为文件
	//	File dest = new File(destPath);//写入目的地 文件可以不存在
		copyFile(new File(scrPath), new File(destPath));
	}	
	/**
	 * 
	 * @param scrPath 数据源对象
	 * @param destPath 拷贝目标对象
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void copyFile(File src,File dest) throws FileNotFoundException,IOException {

		if (!src.isFile()) {
			System.out.println("只能拷贝文件");
			throw new IOException("只能拷贝文件");
		}
		//如果已存在dest文件夹,不能建立与文件夹同名的文件
		if (dest.isDirectory()) {
			System.out.println(dest.getAbsolutePath()+"不能建立与文件夹同名的文件");
			throw new IOException(dest.getAbsolutePath()+"不能建立与文件夹同名的文件");
		}
		//选择流
		InputStream is = new FileInputStream(src);
		OutputStream os = new FileOutputStream(dest);
		//文件拷贝  读取+写入
		byte[] flush = new byte[1024];//接收字节数组
		int len = 0;//定义接收长度
		//循环读取 每次读取长度len,有数据则循环读取,没有数据后结束循环
		while(-1!=(len=is.read(flush))){
			//写入 将字节数组flush从0写入
			os.write(flush, 0, len);
		}
		os.flush();
		//关闭流,先打开的后关闭
		os.close();
		is.close();
		
	}	
	/**
	 * 拷贝文件夹
	 * @param src 源目录
	 * @param dest 目标目录
	 */
	public static void copyDir(File src,File dest){
		if (src.isDirectory()) {
			dest = new File(dest, src.getName());
		}
		copyDirDetail(src,dest);
	}
	
	public static void copyDirDetail(File src,File dest){
		if (src.isFile()) {
			try {
				FileUtil.copyFile(src, dest);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("未找到指定文件");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("拷贝文件失败");
			}
		}else if (src.isDirectory()) {
			//确保目标文件夹存在
			dest.mkdirs();
			File[] subFiles = src.listFiles();
			for (File file : subFiles) {
				copyDirDetail(file, new File(dest,file.getName()));
			}
		}
	}
}

4. 文件夹的拷贝

    1).如果是文件,通过IO流拷贝;
    2).如果是文件夹则通过mkdirs()创建;
    3).使用递归方法搜索文件夹下多重子目录、文件

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 拷贝文件夹
 * 	1.如果是文件,通过IO流拷贝;
 * 	2.如果是文件夹则通过mkdirs()创建;
 * 	3.使用递归方法搜索文件夹下多重子目录(创建)、文件(io流复制)
 * @author Administrator
 *
 */
public class CopyDir {
	public static void main(String[] args) {
		//数据源路径
		String srcPath = "D:/CER/img";
		//拷贝目标路径
		String destPath = "D:/CER/img/s";
		//构建File对象
		File src = new File(srcPath);
		File dest = new File(destPath);
		copyDir(src,dest);
	}
	
	public static void copyDir(File src,File dest){
		if (src.isDirectory()) {
			dest = new File(dest, src.getName());
		}
		copyDirDetail(src,dest);
	}
	
	public static void copyDirDetail(File src,File dest){
		if (src.isFile()) {
			try {
				FileUtil.copyFile(src, dest);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("未找到指定文件");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("拷贝文件失败");
			}
		}else if (src.isDirectory()) {
			//确保目标文件夹存在
			dest.mkdirs();
			//寻找子目录
			File[] subFiles = src.listFiles();
			for (File file : subFiles) {
				copyDirDetail(file, new File(dest,file.getName()));
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_30007589/article/details/81082786