顽皮猫喵 2017-07-25 01:56 采纳率: 71.4%
浏览 2819
已采纳

Spring框架中为什么FileCopyUtils没有用呢?

程序代码很简单:
package com.mzy.domain;

import org.junit.jupiter.api.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.OutputStream;

/**

  • Created by miaozhiyan on 2017/7/24.
    */
    public class Test3 {
    public static void main(String[] args) {
    try {
    Resource resource1 = new ClassPathResource("img/tex1.txt");
    InputStream is1 = resource1.getInputStream();

        Resource resource2 = new ClassPathResource("img/tex2.txt");
        InputStream is2 = resource2.getInputStream();
    
        System.out.println("res1:"+resource1.getFilename());
        System.out.println("res2:"+resource2.getFilename());
    
        EncodedResource encRes1 = new EncodedResource(resource1,"UTF-8");
        String content1 = FileCopyUtils.copyToString(encRes1.getReader());
        System.out.println("content1:"+content1);
    
        FileCopyUtils.copy(resource1.getFile(),new File(resource2.getFile().getParent()+"tex..txt"));
    
        byte [] b1 = FileCopyUtils.copyToByteArray(is1);
        FileCopyUtils.copy(b1,resource2.getFile());
    
        EncodedResource encRes2 = new EncodedResource(resource2,"UTF-8");
        String content2 = FileCopyUtils.copyToString(new FileReader(resource2.getFile()));
        System.out.println("content2:"+content2);
    }catch (Exception e){
    
    }
    

    }
    }

可是为什么输出都输出出来了,打开文件,里面还是空的?tex2是空的,tex3也没有?这是为什么啊?

  • 写回答

1条回答 默认 最新

  • 关注

    String content2 = FileCopyUtils.copyToString(new FileReader(resource2.getFile()));

    System.out.println("content2:"+content2);
    
        不知道你最后这是干嘛,还用reader,不是应该用printwriter之类的吗
        这个给你参考一下:
    

    try {
    FileOutputStream os=new FileOutputStream(new File("d:/22.jpg"));//被复制到此文件中
    Resource resource=new ClassPathResource("/1.jpg"); //文件源 :找类文件下的这个.jpg文件
    FileCopyUtils.copy(resource.getInputStream(),os);

    PS:(

    //FileOutputStream os=new FileOutputStream(new File(fpt+".jpg"));

    //FileSystemResource resource = new FileSystemResource( "E:/union.jpg");

    //FileCopyUtils.copy(resource.getInputStream(),os);

    FileStstemResource //根据文件路径找

    )

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch