java 读取各种类型的文件 (三)

后端java,springboot 、前端vue: 对 txt文件的读写,以及前端预览

一、后端读

  public void readTxt() {

                InputStreamReader input = null;
BufferedReader buffer_reader = null;
          ArrayBlockingQueue<String[]> fileData = new
ArrayBlockingQueue<String[]>(50000);
                try {
input = new InputStreamReader(new FileInputStream(new File(xxx)), Charset.forName("UTF-8"));
buffer_reader = new BufferedReader(input, 2048); // 2MB 缓存空间
String line_str = null;
while ((line_str = buffer_reader.readLine()) != null) {
String[] lines = line_str.split(regexStr);
fileData.put(lines);
}
} catch (Exception e) {
try {
buffer_reader.close();
} catch (Exception e1) {
}
try {
input.close();
} catch (Exception e1) {
}
LOGGER.error("读取TXT文件失败{}",e);
}
}
}
二、后端写
public void run() {
File file = new File("X:/new.txt");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
try {
bufferedWriter.write("hello,world!\nI like the world!");
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
三、前后端配合预览
  1、controller类中
 
public ResponseEntity<byte[]> previewFile(@RequestBody FileVO fileVO) {
        if(fileVO == null || fileVO.getId() == null){
return null;
}
String filename = fileVO.getFileName();
byte[] buffer = getTxTBytes(
fileVO,30);
    HttpHeaders headers = new HttpHeaders();
        //防止中文名乱码
//filename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
try {
headers.setContentDispositionFormData("attachment", filename=java.net.URLEncoder.encode(filename, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
headers.add(HttpHeaders.CONTENT_TYPE,"application/octet-stream;charset=UTF-8");
headers.add("file-type",smsTaskFile.getFileType());
//返回
return new ResponseEntity<byte[]>(buffer, headers, HttpStatus.CREATED);
}
   private byte[] getTxTBytes(FileVO fileVO, int preLines) {
  byte[] fileBuffer = null;
  int readLine = 0;
  InputStreamReader reader = null;
  BufferedReader buffer_reader = null;
  try {
   reader = new InputStreamReader(new FileInputStream(fileVO.getFilePath()), Charset.forName("UTF-8"));
       buffer_reader = new BufferedReader(reader, 20480); // 2MB 缓存空间
      String line_str = null;
          StringBuilder content = new StringBuilder("");
   while ((line_str = buffer_reader.readLine()) != null && readLine < preLines) {
   content.append(line_str).append("\n");
   readLine++;
   }
   fileBuffer = content.toString().getBytes(StandardCharsets.UTF_8);
   } catch (Exception e) {
   try {
   buffer_reader.close();
   } catch (Exception e1) {
   }
   try {
   reader.close();
   } catch (Exception e1) {
   }
   LOGGER.error("读取TXT文件失败{}",e);
   }
   return fileBuffer;
  }
  2、vue
<el-button v-if="item.key == 'operate'" @click.stop="taskfilePreview(scope.row)" type="text" size="small">预览</el-button>

<el-dialog-side :visible="showPreviewFile" @close="showPreviewFile = false;fileContent=''">
  <h1>只预览文件前30行</h1><br>
<el-card>
<el-input v-if="fileContent"
v-model="fileContent"
show-word-limit
:autosize="{ minRows: 12}"
type="textarea"
></el-input>
</el-card>
</el-dialog-side>

taskfilePreview(row){
const reader = new FileReader();
  //通过readAsArrayBuffer将blob转换为ArrayBuffer对
Actions.previewFile(row).then(res => {
if (res.data) {
reader.readAsText(res.data) // 这里的res.data是blob文件流
reader.onload = (event) => {
var data = event.target.result;
this.showPreviewFile = true
this.fileContent = data
}
}
})
}
 
posted @ 2023-08-23 16:03  小魔魔  阅读(25)  评论(0编辑  收藏  举报