通过文件流下载文件

public static void main(String[] args) throws IOException {
        //目标路径
        String filePath = "E:"+File.separator+"test"+File.separator;
        File file = new File(filePath);
        //如果文件目录不存在,就执行创建        
        if(!file.isDirectory()){
            file.mkdirs();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHss");
        //目标文件名称
        String targetName =sdf.format(new Date()) + ".jpg";
        System.out.println(targetName);
        //创建目标文件
        File targetFile = new File(filePath + targetName);
        FileOutputStream fos = new FileOutputStream(targetFile);
        
        //读取本地文件
        File localFile = new File("E:"+File.separator+"1.jpg");
        //获取本地文件输入流
        InputStream stream = new FileInputStream(localFile);
        
        //写入目标文件
        byte[] buffer = new byte[1024*1024];
        int byteRead = 0;
        while((byteRead=stream.read(buffer))!=-1){
            fos.write(buffer, 0, byteRead);
            fos.flush();
        }
        fos.close();
        stream.close();
    }

 

 

import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.commons.io.IOUtils;

public static void main(String[] args) {
	File file1 = new File("C:\\app\\jingjing.txt");
	File file2 = new File("C:\\app\\xinxin.txt");
	String str = "连我生日都记不住";
	try{
		OutputStream outputStream = new FileOutputStream(file2);
		outputStream.write(str.getBytes());
		InputStream inputStream2 = new FileInputStream(file2);
		OutputStream outputStream1 = new FileOutputStream(file1);
		IOUtils.copy(inputStream2,outputStream1);
		IOUtils.closeQuietly(inputStream2);
		IOUtils.closeQuietly(outputStream);
		IOUtils.closeQuietly(outputStream1);
	}catch (Exception e){
		
	}   
}

  

 

posted @ 2022-04-28 16:00  忆舒  阅读(323)  评论(0)    收藏  举报