File-InputStrem/OutputStrem

IO

Java中使用IO(输入输出)来读取和写入,读写设备上的数据、硬盘文件、内存、键盘…,根据数据的走向可分为输入流和输出流,这个走向是以内存为基准的,即往内存中读数据是输入流,从内存中往外写是输出流。

Input(输入):是一个从外界进入到程序的方向,通常我们需要“读取”外界的数据时,使用输入。所以输入是用来读取数据的

Output(输出):是一个从程序发送到外界的方向,通常我们需要“写出”数据到外界时,使用输出。所以输出是用来写出数据的

InputStream 是所有字节输入流的父类,其定义了基础的读取方法,如下:

  1. int read():读取一个字节,以int形式返回,该int值的“低8位”有效,若返回值为-1则表示EOF
  2. int read(byte[] d):尝试最多读取给定数组length个字节并存入该数组,返回值为实际读取到的字节量

OutputStream 是所有字节输出流的父类,其定义了基础的写出方法,如下:

  1. void write(int d):写出一个字节,写的是给定的int的“低8位”
  2. void write(byte[] d):将给定的字节数组中的所有字节全部写出

实例

	public static void readFile(String pathName) {
		try (
			FileInputStream input = new FileInputStream(new File(pathName));
				){
			byte[] b = new byte[1024];
			int len = 0 ;
			StringBuffer sb = new StringBuffer();
			while( (len=input.read(b)) != -1) {
				sb.append(new String(b,0,len));
			}
			System.out.println(sb);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static void writeFile(String pathName,String str) {
		try (
				//加上 true 为在文件中追加内容,默认为False
			FileOutputStream output = new FileOutputStream(new File(pathName),true);
				){
			output.write(str.getBytes());
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static void copyFile(String sourcePath,String targetPath) {
		long begin = System.currentTimeMillis();
		try (
			FileInputStream input = new FileInputStream(new File(sourcePath));
			FileOutputStream output = new FileOutputStream(new File(targetPath));
				){
				int len = 0 ;
				byte[] b = new byte[1024];
				while( (len = input.read(b)) != -1) {
					output.write(b, 0, len);
				}
		} catch (Exception e) {
		}
		System.out.println("文件复制耗时为:"+(System.currentTimeMillis() - begin)+"毫秒");
	}
	
    public static void dateMutualString() throws ParseException {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
		String date = "2018-04-25 10:05:21";
		long time = new Date().getTime();
		System.out.println(simpleDateFormat.format(time).getClass());
		System.out.println(simpleDateFormat.parse(date).getClass());
	}

var foo = 'bar';
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值