zoukankan      html  css  js  c++  java
  • 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?
    因为文件复制,一旦你调用一个属性,另外一个的属性也会跟着变,都是指向同一个地址,所以不能直接复制
  • 相关阅读:
    PSP总结报告
    第十三周例行报告
    对团队成员公开感谢
    附加作业 软件工程原则的应用实例分析
    第十二周例行报告
    第十一周例行报告
    第十周例行报告
    第八周例行报告
    第七周例行报告
    第六周例行报告
  • 原文地址:https://www.cnblogs.com/foreverstudy/p/10904037.html
Copyright © 2011-2022 走看看