Java - IO入門實現簡單的轉存
阿新 • • 發佈:2020-11-16
不多bibi直接上程式碼~
package fileStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.UUID; public class FileSaveUtils { /** * 接收路徑 * 這裡需要接收一個絕對路徑或相對路徑只要能找到檔案即可 * @return * @throws IOException */ public static String fileInputPath(String is) { //將接收到的路徑處理分離 String[] newIs=is.split("/"); String name=newIs[newIs.length-1]; //獲取拓展名 File file = new File(name); String fileName = file.getName(); String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); try { //這裡返回了一個檔名及拓展名xxx.ppt String fileOutputPath = fileOutputPath(suffix,is); return fileOutputPath; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } /** * 存放路徑 * name檔案的拓展名 * is檔案路徑 * @return * @throws IOException */ static private String fileOutputPath(String name,String is) throws IOException{ //獲取UUID String uuid = UUID.randomUUID().toString(); uuid = uuid.replace("-", ""); //設定儲存路徑,這裡將檔名改為uuid隨機名 String o = "F:/檔案檢視/"; String os = o+uuid+"."+name; String path = uuid+"."+name; //建立資料夾 File file = new File(o); file.mkdirs(); fileSave(is,os); return path; } /** * 檔案轉存 * @param is * @throws IOException */ static private void fileSave(String is,String os) throws IOException{ //讀取流物件,和檔案相關聯 FileInputStream fis = new FileInputStream(is); //寫入流物件,明確儲存檔案地址 FileOutputStream fos = new FileOutputStream(os); //將輸入位元組流物件和輸出位元組流物件跟緩衝物件關聯 BufferedInputStream bufis = new BufferedInputStream(fis); BufferedOutputStream bufos = new BufferedOutputStream(fos); //再次定義緩衝區 byte[] buf = new byte[1024]; int len = 0; while((len=bufis.read(buf))!=-1){ bufos.write(buf,0,len); }; bufis.close(); bufos.close(); } }
拜拜~