方法实现
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 }