文件复制

来源:互联网 发布:java流行开源框架 编辑:程序博客网 时间:2024/06/05 05:41

1.梳理: 输入流(读)   输出流(写)

   字节:FileInputStream FileOutputStream

   字符:FileReader FileWriter

2.代码:

第一种方式:

1.首先确认你要下载的文件的路径(path

2.可使用字节输入流:

FileInputStream fis=new FileInputStream(path);

3.为了方便读取大型文件,我们可以使用缓冲流:

BufferedInputStream bis=new BufferedInputStream(fis);

4.用字节流将读取的文件写入你想要放的地方(path2):

FileOutputStream fos=new FileOutputStream(path2);

5.这里同样可以使用缓冲流:

BufferedOutputStream bos=new BufferedOutputStream(fos);

6.进行写的操作:

定义一个int类型的数:

int len=0;

定义一个byte数组,中括号中填写以多大进行读取:

byte[] b=new byte[1024];

使用循环边读边写:

while((len=bis.read(b))!=-1){

bos.write(b, 0, len);

 }

关闭流:(从下往上关)

bos.close();

fos.close();

bis.close();

fis.close();

第二种方式:(使用开源码)

1.确认你要下载的图片的路径(path):

File file=new File(path);

2.确认你要把文件写到何处(path2):

File fileOut=new File(path2);

3.使用开源码:

FileUtils.copyFile(file,fileOut);

注意:当我们要写入某一个地方时,最好先判断该位置是否已存在该文件:

确认该位置路径(path

File file=new File("test.txt");

使用exists()方法进行判断

如果不存在可使用createNewFile()方法创建文件

原创粉丝点击