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?
因為文件復制,一旦你調用一個屬性,另外一個的屬性也會跟着變,都是指向同一個地址,所以不能直接復制