11级_Java_曹建波5.14 字节流

字节流

抽象基类InputStream、OutputStream

字节流可以操作任何数据

字符流使用的是字符数组;字节流使用的是字节数组

实例9,FileInputStream和FileOutputStream的使用。

FileOutputStream fos = newFileOutputStream("a.txt");

fos.write("abcde");//直接将数据写入到了目的地。

fos.close();//只关闭资源。

FileInputStream fis = new FileInputStream("a.txt");

//fis.available();//获取关联的文件的字节数。

//如果文件体积不是很大,可以这样操作。

byte[] buf = new byte[fis.available()];//创建一个刚刚好的缓冲区。但是这有一个弊端,就是文件过大,大小超出jvm的内容空间时,会内存溢出。

fis.read(buf);

System.out.println(new String(buf));

实例9,编写程序copy一个图片。

BufferedInputStream bufis = newBufferedInputStream(new FileInputStream("1.jpg"));

BufferedOutputStream bufos = newBufferedOutputStream(new FileOutptStream("2.jpg"));

int by = 0;

while((by=bufis.read())!=-1){

bufos.write(by);

}

bufos.close();

bufis.close();

自动更新实例

package com.hbsi;

import java.io.*;

importjava.text.SimpleDateFormat;

import java.util.Date;

publicclass FileUpdate {

publicstaticvoid main(String[]args) throws IOException{

Stringfname="source.txt";

Stringdestdir="backup";

update(fname,destdir);

}

publicstaticvoid update(Stringfname,String destdir) throws IOException{

Filef1=new File(fname);

Filedest=new File(destdir);

if (f1.exists()){

if(!dest.exists()){

dest.mkdir();

}

Filef2=new File(dest,fname);

long d1=f1.lastModified();

longd2=f2.lastModified();

if((!f2.exists()) ||(f2.exists() && (d1>d2))){

copy(f1,f2);

}

showFileInfo(f1);

showFileInfo(f2);

}else{

System.out.println(f1.getName()+" 文件不存在!");

}

}

publicstaticvoid copy(File f1,Filef2) throws IOException{

FileInputStreamfis=new FileInputStream(f1);

FileOutputStreamfos=new FileOutputStream(f2);

byte[] buf=newbyte[1024];

int len=0;

while((len=fis.read(buf))!= -1){

fos.write(buf,0, len);

}

System.out.println("复制"+f2.getName()+"成功");

fis.close();

fos.close();

}

publicstaticvoid showFileInfo(Filef){

SimpleDateFormatsdf;

sdf=new SimpleDateFormat("yyyy年MM月dd日 hh时mm分");

if(f.isFile()){

Stringfilepath=f.getAbsolutePath();

long l=f.lastModified();

Dated=new Date(l);

String dateformat=sdf.format(d);

System.out.println("文件:"+filepath+"\t"+f.length()+"\t"+dateformat);

}else{

System.out.println("目录:"+f.getAbsolutePath());

File[] files=f.listFiles();

for(int i=0;i<files.length;i++){

showFileInfo(files[i]);

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值