java_io 涉及到文件(txt,圖片)上傳,下載舒萎,讀取文件程储,excel上傳和下載
字符流和字節(jié)流
- UML
字符流
字節(jié)流
[圖片上傳失敗...(image-d5611-1662632030088)]
- 字符流code
字符流輸入
/**
* 屬于字節(jié)流 InputStream 輸入流FileInputStream
* FileInputStream:只能以字節(jié)單位讀取,對漢字不友好臂寝;讀取漢字亂碼章鲤,換成字符流讀取即可
* 從另一角度來說:字符流 = 字節(jié)流 + 編碼表。
*/
public class FileInputStreamTest {
//FileInputStream讀取 txt,中文亂碼
// public static void main(String[] args) throws IOException {
// //創(chuàng)建一個(gè)輸入流咆贬,方便讀取
// FileInputStream fis = new FileInputStream("D:/output4.txt");
//
// //定義一個(gè)字節(jié)數(shù)組咏窿,裝字節(jié)數(shù)據(jù)容器
// byte[] b = new byte[2];
// while (fis.read(b) != -1) {
// //按照每2個(gè)字節(jié)讀取: 一個(gè)英文單詞一個(gè)字節(jié),一個(gè)漢字3個(gè)字節(jié)
// System.out.println(new String(b));
//
// }
// }
//InputStreamReader: 根據(jù)字符讀取素征,但是不能一行一行讀燃丁;解決:使用緩沖流解決
public static void main(String[] args) throws IOException {
//創(chuàng)建一個(gè)輸入流御毅,方便讀取
FileInputStream fis = new FileInputStream("D:/output4.txt");
//轉(zhuǎn)換成字符流的輸入流
Reader reader = new InputStreamReader(fis,"utf-8");
char[] b = new char[2];
int readData;
while (-1 != (readData = reader.read(b))) {
//按照每4個(gè)字節(jié)讀取: 一個(gè)漢字一個(gè)字符
System.out.println(new String(b));
}
}
}
字符流輸出
/**
* 字節(jié)流根欧,OutputStream輸出流:FileOutputStream,ObjectOutputStream
* 寫入不了漢字字符串
*/
public class FileOutputStreamTest {
//FileOutputStream測試
// public static void main(String[] args) throws Exception {
// //定義一個(gè)文件輸出流:相當(dāng)于一個(gè)最終輸出的容器端蛆,以文件形式存在
// FileOutputStream fos = new FileOutputStream("D:/output.txt");
// fos.write(97);//可以寫int
// fos.write("abc".getBytes());//寫字節(jié)
// fos.write("qwer".getBytes(),1,2);//寫指定長度的字節(jié)
// fos.close();//關(guān)閉資源
//
// }
//ObjectOutputStream 功能更強(qiáng)大凤粗,輸出流可以寫 漢字字符串,對象
//解決亂碼:對象沒有序列化,但是寫漢字字符串依然亂碼
//解決漢字亂碼:使用PrintStream
public static void main(String[] args) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:/output2.txt"));
String s = "abc";
oos.writeChars(s);
Map<String, String> map = new HashMap<>();
map.put("name","lg");
map.put("age", "10");
oos.writeObject(JSONObject.toJSONString(map));
oos.close();//關(guān)閉資源
PrintStream printStream = new PrintStream(new FileOutputStream("D:/output3.txt"));
printStream.println("發(fā)的發(fā)但是\n rqwer");
printStream.close();
}
}
字符流讀
/**
* 字符流,讀嫌拣,
* InputStreamReader:按照字符讀取柔袁,效率低
* BufferedReader:按照一行讀取,效率高异逐;字節(jié)流 => 字符流讀 => 緩沖流讀
*/
public class InputStreamReadTest {
//InputStreamReader
// public static void main(String[] args) throws IOException {
// InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("D:/test.txt"));
//
// char[] chars = new char[2];
//
// while (inputStreamReader.read(chars) != -1) {
// System.out.println(new String(chars));
// }
//
// }
// 字節(jié)流 => 字符流讀 => 緩沖流讀
public static void main(String[] args) throws IOException{
Reader reader = new InputStreamReader(new FileInputStream("D:/test.txt"));
BufferedReader bufferedReader = new BufferedReader(reader);
String lineStr = null;
while ((lineStr = bufferedReader.readLine()) != null) {
System.out.println(lineStr);
}
bufferedReader.close();
}
}
字符流寫
/**
* 字符流捶索,寫入,依賴于字節(jié)流
* OutputStreamWriter:只能寫入字符灰瞻,字符串腥例,
* OutputStreamWriter:寫入效率快
*/
public class OutputStreamWriterTest {
//OutputStreamWriter
// public static void main(String[] args) throws IOException,Exception {
// //字符流寫的創(chuàng)建依賴與 字節(jié)流輸出創(chuàng)建
// Writer writer = new OutputStreamWriter(new FileOutputStream("D:/output6.txt"), "utf-8");
//
// writer.write("發(fā)放時(shí)");//
//
// writer.close();
//
// }
//字節(jié)流 =》 字符流 => 緩存字符流 : 效率快
public static void main(String[] args) throws IOException {
Writer writer = new OutputStreamWriter(new FileOutputStream("D:/output6.txt"), "utf-8");
BufferedWriter bufferedWriter = new BufferedWriter(writer);
bufferedWriter.write("Fsdfasd方法士大夫");
bufferedWriter.close();
}
}
- 總結(jié)
- 字符流 比 字節(jié)流 效率慢;字符流適合中文讀寫操作
- 可以使用緩沖流 提升讀寫效率酝润;字節(jié)流 =》 字符流 =》 緩存字符流
- 注意:中文亂碼bug
- 序列化問題
- 編碼格式
上傳和下載
excel上傳和下載
使用第三方的jar
<!-- excel導(dǎo)入和導(dǎo)出工具 easypoi-base-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
- 后臺代碼
//實(shí)體必須加上注解@Excel
@Data
@AllArgsConstructor
public class UserDTO {
@Excel(name = "名稱")
private String name;
@Excel(name = "年齡")
private Integer age;
}
@RequestMapping("/user")
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping("/find")
public String find() {
String s = userService.find();
return s;
}
//上傳功能
@PostMapping("/importExecl")
public String importExecl(@RequestParam("file") MultipartFile file) throws Exception {
// Excel
List<UserDTO> userDTOS = ExcelImportUtil.importExcel(file.getInputStream(), UserDTO.class, new ImportParams());
userDTOS.stream().forEach(v -> System.out.println(v));
//插入數(shù)據(jù)庫操作
return "ok";
}
//導(dǎo)出功能
@GetMapping("/exportExecl")
public String exportExecl(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
List<UserDTO> userDTOS = new ArrayList<>();
userDTOS.add(new UserDTO("FASD",12));
userDTOS.add(new UserDTO("Fdsf",100));
//必須設(shè)置的
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=" + "用戶");
Workbook sheets = null;
ExportParams exportParams = new ExportParams(null,"用戶");
exportParams.setType(ExcelType.XSSF);
ServletOutputStream outputStream = response.getOutputStream();
try {
sheets = ExcelExportUtil.exportBigExcel(exportParams, UserDTO.class, userDTOS);
sheets.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (sheets != null){
sheets.close();
}
ExcelExportUtil.closeExportBigExcel();
}
return "ok";
}
}
- 前端 代碼 jq ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<!-- <script src="./js-file-download-master/file-download.js"></script> -->
</head>
<body>
<input type="file" id="file">
<button id="import">上傳</button>
<button id="export">導(dǎo)出</button>
</body>
<script>
//導(dǎo)出
$("#export").click(() => {
$.ajax({
url: "http://127.0.0.1:8080/user/exportExecl",
method: "GET",
data: null,
processData: false,
contentType: false,
xhrFields: { responseType: "arraybuffer" },//必須設(shè)置燎竖,不然會亂碼
success: function (res) {
console.log(res);
//
const blob = new Blob([res], { type: "application/vnd.ms-excel" });
if (blob.size < 1) {
alert('導(dǎo)出失敗,導(dǎo)出的內(nèi)容為空要销!');
return
}
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, '用戶.xlsx')
} else {
const aLink = document.createElement('a');
aLink.style.display = 'none';
//[關(guān)鍵]
aLink.href = window.URL.createObjectURL(blob);//把二進(jìn)制流轉(zhuǎn)換成下載鏈接
aLink.download = '用戶.xlsx';
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
}
}
})
})
//下載
$("#import").click(() => {
let file = $("#file")[0].files[0];
console.log(file)
let formData = new FormData();
formData.append("file", file);
$.ajax({
url: "http://127.0.0.1:8080/user/importExecl",
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function (res) {
console.log(res);
fileDownload(res, '用戶.xlsx');
}
})
})
$.ajax({
url: "http://127.0.0.1:8080/user/find",
method: "GET",
success: function (res) {
console.log(res);
}
})
</script>
</html>