1. ByteArrayOutputStream
InputStream in = context.openFileInput("datafile.txt"); ByteArrayOutputStream bais = new ByteArrayOutputStream(); byte[] bytes = new byte[8192]; for(int len; (lne = in.read(bytes) > 0;) bais.write(bytes, 0, len); in.close(); return bais.toByteArray();2. FileOutputStream
public static void main(String[] args) throws Exception { byte[] array = new byte[1024*4]; FileInputStream fis = new FileInputStream(new File("<Path-to-input-file>")); FileOutputStream fos = new FileOutputStream(new File("<Path-to-output-file>")); int length = 0; while((length = fis.read(array)) != -1) { fos.write(array, 0, length); } fis.close(); fos.close(); }
3. Use FileChannel
4. Apache Commons IO FileUtils.
FileUtils class
avoid DOS attack từ tầng trình diễn
String content =FileUtils.readFileToString(new File(filePath));
5. Delete temporary files
private void deleteCompressTempFiles(HttpServletRequest request) {
String path = request.getSession().getServletContext().getRealPath("/");
//File file = File.createTempFile("getter", ".html", new File(path + "/tmp/"));
//File dir = new File(path + "/temp/");
File dir = new File(System.getProperty("java.io.tmpdir"));
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
String tmpName = name.toLowerCase();
return tmpName.startsWith("poi-sxssf-sheet") && (tmpName.endsWith(".xml") || tmpName.endsWith(".gz"));
}
});
if (files != null) {
for (File file : files) {
file.delete();
}
}
}
//Absolute file path on server
String serverFileName = updateForm.getServerFileName();
String tempPath = ResourceBundleUtils.getResource("UPLOAD_FILE_PATH");
String serverFilePath = req.getSession().getServletContext().getRealPath(tempPath); //server
String fullServerFileName = tempPath + serverFileName;
File clientFile = new File(fullServerFileName);
String serverFileName = updateForm.getServerFileName();
String tempPath = ResourceBundleUtils.getResource("UPLOAD_FILE_PATH");
String serverFilePath = req.getSession().getServletContext().getRealPath(tempPath); //server
String fullServerFileName = tempPath + serverFileName;
File clientFile = new File(fullServerFileName);
Tham khảo:
0 comments:
Post a Comment