字节流

3.字节流

1.InputStream

方法: - read():int -1 - read(byte[]):int -1 - close():void - FileInputStream主要用于操作文件 - System.in 主要用于 接收用户输入

2.OutputStream

方法: - write(int):void - write(byte[],int,int):void - close():void - FileOutputStream主要用于操作文件 - new FileOutputStream(“文件名称”)采用文件覆盖的方式操作 - new FileOutputStream(“文件名称”,boolean是否采用追 加操作) - System.out和System.err 用于输出到标准输出设备

文件的拷贝

1.由于是一次读取一字节的操作,所以在操作输出时会有问题,但是文件拷贝不会有任何问题

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class T3 {
	public static void main(String[] args)throws Exception {
		//try/resource的写法,会自动执行关闭操作,但是要求实现closeable接口
		try(OutputStream os = new FileOutputStream("aa");
			InputStream is = new FileInputStream("java.txt");
				){
			int kk;
			while((kk=is.read())!=-1) {
				os.write(kk);
			}
		}
	}
}
由于是一次读取一字节的操作,所以在操作输出时会有问题,但是文件拷贝不会有任何问题 

2.引入byte[]缓存的方式提高执行效率

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class T3 {
	public static void main(String[] args)throws Exception {
		//try/resource的写法,会自动执行关闭操作,但是要求实现closeable接口
		try(OutputStream os = new FileOutputStream("aa");
			InputStream is = new FileInputStream("java.txt");
				){
			int kk;
			byte[]buffer = new byte[8192];//如果不确定缓存的大小,建议使用8192,即8kB
			while((kk=is.read(buffer))!=-1) {
				String ss = new String(buffer,0,kk);//解决多字节的字符组装问题
				System.out.println(ss);
				os.write(buffer, 0, kk);//读取多少个字节则写出多少个字节
			}
		}
	}
}

3.实现文件夹的拷贝和移动

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class T3 {
	private static String source;
	private static String target;
	public static void main(String[] args)throws Exception {
		source ="";//源文件路径
		target = "";//拷贝文件的路径
		File f = new File(source);
		
	}
	public static void copy(File file)throws Exception{
		if(file!=null&&file.exists()) {
			if(file.isFile()) {
				String path = file.getAbsolutePath();
				String newpath = path.replace(source, target);
				try(
						InputStream is=new FileInputStream(file);                    
						OutputStream os=new FileOutputStream(newpath); 	
						){
					byte[]buffer = new byte[8192];
					int len =0;
					while((len=is.read(buffer))>0)
						os.write(buffer, 0, len);
				}
				
			}
			if(file.isDirectory()) {
				String path = file.getAbsolutePath();
				String newpath = path.replace(source, target);
				File tmp = new File(newpath);
				if(!tmp.exists())
					tmp.mkdirs();
				File []fs = file.listFiles();
				if(fs!=null&&fs.length>0)
					for(File temp :fs)
						copy(temp);
			}
		}
	}
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值