File 的IO流

IO流的使用

流的分类

  1. 按流向分为:输入和输出
    输入:InputStream、Reader
    输出:OutputStream、Writer
  2. 按类型分为:字节和字符
    字节流:InputStream、OutputStream
    字符流:Reader、Writer
  3. 按功能分为:节点流和处理流

文件IO流的构造方法

输入流:FileReader(File file) 或FileInputStream(File file)

输出流 :
FileWriter(File file)
FileOutputStream(File file)
FileWriter(File file, boolean append)
FileWriter(File file, boolean append)

常用方法

InputStream类Reader
available():获取当前流中的可读字节数read():读取并返回一个字符
close():关闭此流close():关闭此流
read():从流中读取一个字节,返回读取到的字节read(char[] c):将从流中读取的字符存储到字符数组
read(byte[] b,int offset,int len):将流中读取奥的字节存入到指定的字节数组中(跳过offset个字节存储,存储长度为len),读取不到返回-1read(char[] c,int offset,int len):将从流中读取的字符存入字符数组(跳过offset个字节,写入len长)
ready():返回此流是否准备好被读取的状态
OutputStream类Writer
write(byte[] b):将字节数组中的内容写入输出源(文件,网络,内存)append(char c):向流中追加一个字符
write(byte[] b,int offset,int len):将字节数组中的内容从offset开始写入len长到输出源append(CharSequence c):向流中追加一个字符序列(字符串)
write(int b):将一个字节写入输出源witer(String s):写入一个字符串到目标输出源
flush():将流中的数据强制刷新到输出源witer(char[] c):写入字符数组到目标输出源
close():关闭此流

字节流与字符流

字节流字符流
所谓字节流,其实就是将数据以字节为单位进行读写相关操作,字节流一般用于对于一些二进制文件(图片,音频,视频等)进行读写操作字符流,顾名思义,是以字符的形式对输入输出源操作,通常情况下一个字符表示两个字节

文件拷贝功能的实现

public class FileCopy {

/**
 * 将源文件拷贝到目标目录中
 * @param sourceFile 源文件(标准文件)
 * @param targetDir 目标目录(目录)
 */
public void copy(File sourceFile,File targetDir){
	FileInputStream fis = null;
	FileOutputStream fos = null;

	try {
		//获取源文件的输入流
		fis = new FileInputStream(sourceFile);
		//获取目标文件的输出流
		fos = new FileOutputStream(new File(targetDir,sourceFile.getName()));
		//声明字节缓冲区
		byte[] b = new byte[1024];
		//声明变量存储真实读取长度
		int len = 0;
		//循环读取以及写入
		while((len = fis.read(b)) != -1){
			fos.write(b,0,len); 
		}
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}finally{
		try {
            //关闭资源
			if(fos != null){
				fos.close();
			}
			if(fis != null){
				fis.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
		
}

public static void main(String[] args) {
	File source = new File("拷贝文件");
	File target = new File("要拷贝到的地址");
	new FileCopy().copy(source, target); 
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值