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?
    因为文件复制,一旦你调用一个属性,另外一个的属性也会跟着变,都是指向同一个地址,所以不能直接复制
  • 相关阅读:
    VC 常见问题百问
    python windows 环境变量
    Check server headers and verify HTTP Status Codes
    Where are the AES 256bit cipher suites? Please someone help
    outlook 如何预订会议和会议室
    安装Axis2的eclipse插件后,未出现界面
    windows 环境变量
    python 时间日期处理汇集
    openldap学习笔记(使用openldap2.3.32)
    set p4 environment in windows
  • 原文地址:https://www.cnblogs.com/foreverstudy/p/10904037.html
Copyright © 2011-2022 走看看