一:概述
在Java开发中,文件的上传和下载是常见的功能需求,而字符流(Character Stream)的使用则涉及到文件内容的读取和写入。本文将详细介绍Java中实现文件上传、下载以及字符流使用的不同方法,并提供实际案例和图解。
二:具体说明
<1>文件上传
1.1 使用Servlet 3.0+的Part接口
Servlet 3.0引入了Part接口,使得文件上传变得更加简单。
示例代码:
@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part filePart = request.getPart("file"); // "file"是表单中的字段名
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
InputStream fileContent = filePart.getInputStream();
// 保存文件
Files.copy(fileContent, Paths.get("uploadPath", fileName), StandardCopyOption.REPLACE_EXISTING);
}
}
2.2 使用Apache Commons FileUpload
Apache Commons FileUpload是一个强大的文件上传库。
示例代码
public class FileUploadUtil {
public static List<File> uploadFiles(HttpServletRequest request) throws Exception {
List<File> files = new ArrayList<>();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
File uploadedFile = new File("uploadPath" + File.separator + item.getName());
item.write(uploadedFile);
files.add(uploadedFile);
}
}
} catch (Exception e) {
throw new Exception("Error in file upload", e);
}
return files;
}
}
<2>文件下载
2.1 使用Servlet
Servlet提供了一种直接的方法来实现文件下载。
示例代码
@WebServlet("/download")
public class FileDownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = "example.txt";
response.setContentType("application/octet-stream");
response.setContentLength((int) new File("uploadPath", fileName).length());
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
Files.copy(new File("uploadPath", fileName).toPath(), response.getOutputStream());
}
}
2.2 使用Spring MVC
Spring MVC提供了更简洁的文件下载方法。
示例代码
@RequestMapping("/download")
public ResponseEntity<Resource> downloadFile() {
String fileName = "example.txt";
Resource resource = new FileSystemResource("uploadPath" + File.separator + fileName);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.body(resource);
}
<3>字符流的使用
3.1 读取文件内容
使用BufferedReader
可以高效地读取文件中的文本内容。
示例代码
public String readFile(String filePath) throws IOException {
StringBuilder contentBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String currentLine;
while ((currentLine = br.readLine()) != null) {
contentBuilder.append(currentLine).append("\n");
}
}
return contentBuilder.toString();
}
3.2 写入文件内容
使用BufferedWriter
可以将文本内容写入文件。
示例代码
public void writeFile(String filePath, String content) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, true))) {
bw.write(content);
}
}
<4>总结
本文详细介绍了Java中文件上传、下载以及字符流的使用,并给出了实际代码示例。无论是使用Servlet、Apache Commons FileUpload还是Spring MVC,都有其适用场景和优势。字符流的使用则为文件内容的读写提供了灵活的方式。希望本文能够帮助开发者在实际项目中高效地实现文件操作功能。