• java上传txt文件,出现中文乱码


    public String uploadBook(MultipartFile file, Book book, HttpServletRequest request) {
        try{
    String lineTxt = null;
    String content="";
    List<String> titlelist=new ArrayList<String>();
    InputStream inputStream = null;//获得字节流
    if(!file.isEmpty()){

    InputStreamReader inputStreamReader=null;
    String url = request.getSession().getServletContext().getRealPath("/upload");
    String realPath=url+file.getOriginalFilename();
    File tempFile=new File(realPath);
              //把文件上传到指定的位置
    file.transferTo(tempFile);
              //new 两个字节流
                    InputStream ins1=new FileInputStream(tempFile);
    InputStream ins2=new FileInputStream(tempFile);
              //new 第一个是用来读取txt前几个字节,来判断编码格式,因为你不确定上传上来的到底是什么格式
                    byte[]ch=new byte[1024];
    ins1.read(ch);
    if(Utf8Util.isUtf8(ch)){
                //第二个用来读取txt内容
    inputStreamReader = new InputStreamReader(ins2,"UTF-8");//获得字符流
    }else{
    inputStreamReader = new InputStreamReader(ins2,"GBK");//获得字符流
    }
    ins1.close();

    // InputStreamReader inputStreamReader = new InputStreamReader(inputStream);//获得字符流
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);//缓存数据用于读取
    while((lineTxt = bufferedReader.readLine())!= null) {
    if(validReg(lineTxt)&&lineTxt.length()<100){
    titlelist.add(lineTxt);
    content=content+"####";
    }else{
    if(StringUtils.isNotEmpty(lineTxt.trim())){
    content+="<p>"+lineTxt+"</p>";
    }
    }
    }
              //读完之后,别忘了把文件删除,删除之前先把流关上
              bufferedReader.close();
              ins2.close();
              tempFile.delete();
                    if(StringUtils.isNotEmpty(content)){
    String chapterlist[]=content.split("####");
    if(chapterlist.length>0){
    for(int i=1;i<chapterlist.length;i++){
    chapter.setWords(String.valueOf(msg.length()));
    chapter.setContent(msg);
    chapterMapper.insertChapter(chapter);
    }
    }
    }
    }
    return "导入成功!";
    }catch (Exception e){
    e.printStackTrace();
    return "导入失败!";
    }
    }

    注解:为什么要new 两个ins?
    因为,读取文件之后
    byte[]ch=new byte[1024];
    ins1.read(ch);
    1的指针已经指向后1024个字节,如果继续读取,就会丢失前面判断编码的,大小的字节内容,所以要new 两个
    为什么不直接用filetemp=file?
    因为文件复制,一旦你调用一个属性,另外一个的属性也会跟着变,都是指向同一个地址,所以不能直接复制
  • 相关阅读:
    LR实战之Discuz开源论坛——安装及简介
    LR如何利用siteScope监控MySQL性能
    初学SSH(其一)
    使用JUnit单元测试入门
    理解java中【同步】和【死锁】
    LR性能测试应用
    (28)ElasticSearch分布式架构特点
    (27)ElasticSearch 复合查询
    (06)Gitlab设置开启自启动、关闭开机自启动
    (05)安装GitLab
  • 原文地址:https://www.cnblogs.com/foreverstudy/p/10904037.html
Copyright © 2020-2023  润新知