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

public String uploadBook(MultipartFile file, Book book, HttpServletRequest request) {

try{

String lineTxt = null;

String content="";

List titlelist=new ArrayList();

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+="

"+lineTxt+"

";

}

}

}

//读完之后,别忘了把文件删除,删除之前先把流关上

bufferedReader.close();

ins2.close();

tempFile.delete();

if(StringUtils.isNotEmpty(content)){

String chapterlist[]=content.split("####");

if(chapterlist.length>0){

for(int i=1;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?

因为文件复制,一旦你调用一个属性,另外一个的属性也会跟着变,都是指向同一个地址,所以不能直接复制

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值