標籤:mob rpo path aaaaa vdi buffer api rdo mtd
工程結構
1.產生一個檔案到指定檔案夾下
//產生一個唯一的名字this.setFileName(String.valueOf(System.currentTimeMillis()));String path = ServletActionContext.getServletContext().getRealPath("/template/WordExportTemplate");//工程下的完整路徑名String filepath = path +"\\" + fileName + ".doc";//寫入檔案Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath,true), "utf-8"), 10240);out.write(" ");
2.將指定檔案下的檔案輸出到用戶端(將上面產生的檔案輸出)
public InputStream getInputStream() throws Exception { create(); String path = ServletActionContext.getServletContext().getRealPath("/template/WordExportTemplate"); String filepath = path +"\\" + fileName + ".doc"; //完整的路徑名 File file = new File(filepath); //只用返回一個輸入資料流 return FileUtils.openInputStream(file); }
3.將用戶端上傳的檔案以特定名字存到指定檔案夾下:
public String execute() throws Exception{ ServletContext servletContext = ServletActionContext.getServletContext();// fileNameFileName表示檔案上傳時候的名字,也可以自己用UUID定義一個新的名字 String dir = servletContext.getRealPath("/template/ExcelImportTemplate/"+fileNameFileName); System.out.println(dir);// 檔案輸出資料流,寫到dir指定的目錄與名字 FileOutputStream outputStream = new FileOutputStream(dir);// 開啟上傳的檔案的輸入資料流 FileInputStream inputStream = new FileInputStream(fileName); byte[] buffer = new byte[1024]; int len = 0;// 從此輸入資料流中將最多 b.length 個位元組的資料讀入一個 byte 數組中.讀入緩衝區的位元組總數,如果因為已經到達檔案末尾而沒有更多的資料,則返回 -1。 while((len = inputStream.read(buffer))!=-1){// 將指定 byte 數組中從位移量 off 開始的 len 個位元組寫入此檔案輸出資料流。 outputStream.write(buffer, 0, len); } inputStream.close(); outputStream.close(); return SUCCESS; }
4.讀取指定檔案夾下指定名字的檔案:
ServletContext servletContext = ServletActionContext.getServletContext();
// fileNameFileName表示檔案上傳時候的名字,也可以自己用UUID定義一個新的名字
String dir = servletContext.getRealPath("/template/ExcelImportTemplate/"+fileNameFileName);
File file = new File(dir);
FileInputStream openInputStream = FileUtils.openInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(openInputStream);
5. FileInputStream FileOutputStream是類。可以直接讀取與寫。
構造方法
例如:
public InputStream getInputStream() throws Exception { create(); String path = ServletActionContext.getServletContext().getRealPath("/template/ExcelExportTemplate"); String filepath = path +"\\" + fileName + ".xls"; File file = new File(filepath); //只用返回一個輸入資料流 return FileUtils.openInputStream(file); }
String path = ServletActionContext.getServletContext().getRealPath("/template");File tempFile = new File(path, templateName + ".xls");tempFile.delete();tempFile.createNewFile();
FileOutputStream stream = FileUtils.openOutputStream(tempFile);
1 ServletContext servletContext = ServletActionContext.getServletContext();2 // fileNameFileName表示檔案上傳時候的名字,也可以自己用UUID定義一個新的名字3 String dir = servletContext.getRealPath("/template/ExcelImportTemplate/"+fileName);4 FileOutputStream outputStream = new FileOutputStream(dir);
Web下檔案上傳下載的路徑問題