一般文件导出(文件流)
文件加密
创建文件夹
package tools.attachment;
import org.apache.commons.codec.CharEncoding;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class AttachmentUtil {
public static void export(String filePath, HttpServletResponse response) {
try {
File file = new File(filePath);
String filename = file.getName();
InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.setCharacterEncoding(CharEncoding.UTF_8);
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException e) {
throw new RuntimeException("系统找不到指定的文件!");
} finally {
}
}
public static void encrypt(String filePath, String password){
if(!StringUtils.isEmpty(password)){
FileOutputStream fos=null;
try {
File file = new File(filePath);
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
Encryptor enc = info.getEncryptor();
enc.confirmPassword(password);
OPCPackage opc = OPCPackage.open(file, PackageAccess.READ_WRITE);
OutputStream os = enc.getDataStream(fs);
opc.save(os);
opc.close();
fos = new FileOutputStream(file);
fs.writeFilesystem(fos);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static boolean createDir(String filePath) {
File dir = new File(filePath).getParentFile();
if (dir.exists()) {
return true;
}
if (dir.mkdirs()) {
return true;
} else {
return false;
}
}
}