將輸入流形式的文件存儲到本地


方法實現

 1   /**
 2      * 將輸入流形式的文件存儲到本地
 3      * @param filePath 文件存儲的目錄
 4      * @param fileName 文件名稱
 5      * @return
 6      */
 7     public static File saveUrlAs(String filePath,String fileName){
 8          //創建不同的文件夾目錄
 9          File file = new File(filePath);
10          //判斷文件夾是否存在
11          if (!file.exists()){
12             //如果文件夾不存在,則創建新的的文件夾
13              file.mkdirs();
14         }
15          FileOutputStream fos = null;
16          InputStream is = null;
17          BufferedInputStream bis = null;
18          BufferedOutputStream bos = null;
19          try{
20              File f = new File("E:/test.txt");
21              is = new FileInputStream(f);
22              bis = new BufferedInputStream(is);
23              //判斷文件的保存路徑后面是否以/結尾
24              if (!filePath.endsWith("/")) {
25                  filePath += "/";
26              }
27              //寫入到文件(注意文件保存路徑的后面一定要加上文件的名稱)
28              fos = new FileOutputStream(filePath+fileName);
29              bos = new BufferedOutputStream(fos);
30              byte[] buf = new byte[4096];
31              int length = bis.read(buf);
32              //保存文件
33              while(length != -1){
34                  bos.write(buf, 0, length);
35                  length = bis.read(buf);
36              }
37         } catch (Exception e){
38              e.printStackTrace();
39              System.out.println("拋出異常!!");
40         } finally {
41             if(bos != null) {
42                 try {
43                     bos.close();
44                 }catch(Exception e) {
45                     e.printStackTrace();
46                 }
47             }
48             if(bis != null) {
49                 try {
50                     bis.close();
51                 }catch(Exception e) {
52                     e.printStackTrace();
53                 }
54             }
55         }
56         return file;
57      }

方法調用

1   public static void main(String[] args) {
2         String filePath = "D:/112233/"; 
3         File saveUrlAs = saveUrlAs( filePath,"test2.txt"); 
4         System.out.println(saveUrlAs);
5   }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM