Java 文件处理

Java 文件处理


1、获取文件-文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class UtilFile {

/**
* 递归获取某个文件夹下的所有文件
*
* @param fileNameList
* 存放文件名称的list
* @param path
* 文件夹的路径
* @return 文件名称
*/
public static ArrayList<String> getAllFileName(String path, ArrayList<String> fileNameList) {
ArrayList<String> files = new ArrayList<String>();
File file = new File(path);
File[] tempList = file.listFiles();

for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
// 文件路径
// System.out.println("文 件:" + tempList[i]);
// fileNameList.add(tempList[i].toString());
String fName = tempList[i].toString();
File tempFile = new File(fName.trim());
String fileName = tempFile.getName();
// System.out.println("fileName = " + fileName);
// 获取文件名称添加入list
files.add(fileName);
fileNameList.add(tempList[i].getName());
}
if (tempList[i].isDirectory()) {
// 文件夹路径
// System.out.println("文件夹:" + tempList[i]);
getAllFileName(tempList[i].getAbsolutePath(), fileNameList);
}
}
return files;
}

public static void main(String[] args) {
ArrayList<String> files = new ArrayList<String>();
files = UtilFile.getAllFileName("E:/apache-tomcat-8.5.15/webapps/mexx/excel", new ArrayList<String>());
for (String string : files) {
System.out.println("文件名:" + string);
}

}

}
  • files:返回的文件名
  • tempList[i].toString():获取到的文件或文件夹完整路径

重点

省去了切割字符串,步骤,避免在不同平台路径问题,直接可以拿到路径最后的文件名
1
2
3
4
String fName ="E:/apache-tomcat-8.5.15/webapps/mexx/excel";
File tempFile = new File(fName.trim());
String fileName = tempFile.getName();
System.out.println("fileName = " + fileName);

2、文件下载 Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
   /**
* 文件下载
*
* @throws IOException
*/
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(@RequestParam(value = "filename") String filename, HttpServletRequest request,
HttpServletResponse response) throws IOException {

// 模拟文件,myfile.txt为需要下载的文件
//String path = request.getSession().getServletContext().getRealPath("Excel") + "\\" + filename;
String path =EXCEL_URL + "/" + filename;
// 获取输入流
InputStream bis = new BufferedInputStream(new FileInputStream(new File(path)));
// 转码,免得文件名中文乱码
filename = URLEncoder.encode(filename, "UTF-8");
// 设置文件下载头
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
// 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int len = 0;
while ((len = bis.read()) != -1) {
out.write(len);
out.flush();
}
out.close();
System.out.println(ExcelController.getIpAddr(request)+"下载完成");
}

3、前端显示

1
2
3
4
5
<div style="margin-top:30px;">
<c:forEach items="${filesList }" var="fileName" >
<button type="button" >${fileName}</button>
</c:forEach>
</div>