通过文件流下载文件

复制代码
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();
    }
复制代码

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 @   忆舒  阅读(300)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示