项目完结了,总结一下开发过程中,遇到到的问题,整理一下自己的用到的工具类,以后用到了可以直接使用。当时遇到的这个需求就是对文件进行数据封装,对文件按照要求生成多级目录,将服务器上的文件放到这个文件夹中,然后封装。当时遇到的问题是如果直接对文件夹生成过程中添加.zip的后缀,就会只对最后一成绩文件夹封装,我们想要的见整个文件夹封装。最后的实现的思路就是创建一个新的文件夹,对其进行封装,然后将我们按照标准生成的文件夹拷贝到该文件夹下。
public static void copyFolder(String oldPath, String newPath, List fileList) {
try {
if(!new File(newPath).exists()){
(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
}
File a = new File(oldPath);
if (a.exists()) {
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
if (temp.isFile()) {
String fileName = temp.getName();
Optional tempFile =
fileList.stream().filter(dzgdFile -> dzgdFile.getFname().equals(fileName))
.findFirst();
if(tempFile != null && tempFile.isPresent()){
String name = tempFile.get().getElectronicDocumentName();
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath
+ “/” + name + fileName.substring(fileName.indexOf(“.”)));
byte[] b = new byte[1024 * 20];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}else{
System.out.println(“--------------------------------------------” + fileName);
}
}
if (temp.isDirectory()) {// 如果是子文件夹
copyFolder(oldPath + “/” + file[i], newPath + “/” + file[i], fileList);
}
}
}
} catch (Exception e) {
System.out.println(“复制整个文件夹内容操作出错”);
e.printStackTrace();
}
}
上述代码就是可以直接使用的工具类,fileList代表的是在服务器上查询到的文件,将查询到的文件直接添加,如果更改就换成自己查询到的文件;下面的工具类是直接移动文件夹到指定位置(文件夹下已经有内容了)
public static void copyFolder(String oldPath, String newPath) {
try {
(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File a = new File(oldPath);
if (a.exists()) {
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath
+ “/” + (temp.getName()).toString());
byte[] b = new byte[1024 * 20];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夹
copyFolder(oldPath + “/” + file[i], newPath + “/” + file[i]);
}
}
}
} catch (Exception e) {
System.out.println(“复制整个文件夹内容操作出错”);
e.printStackTrace();
}
}