1、编写代码
main方法:
public static void main(String[] args) throws IOException { String pathFileUrl ="C:/Users/xxx/Desktop/boardDevice/videoFiles/1677749222547.docx"; //String pathFileUrl ="D:\\images\\6d3a8ae483ba9016284d582b3af98670.png"; //String pathFileUrl ="D:\\boardDevice\\video\\1677829260585.mp4"; copyFileLogic(pathFileUrl); }
copyFileLogic处理路径信息:
public static void copyFileLogic(String oldPath) throws IOException { String newPath = "C:/Users/xxx/Desktop/boardDevice/copyFiles"; File file = new File(newPath); if (!file.exists()){ file.mkdirs(); } String[] split = oldPath.split("/"); String fileName = split[split.length - 1]; String suffix = fileName.split("\\.")[1]; String files = newPath +"/"+System.currentTimeMillis()+"."+suffix; copyFileMethod(oldPath,files); }
copyFileMethod文件拷贝:
public static void copyFileMethod(String oldPath,String newPath) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; BufferedOutputStream bos = null; try { fis = new FileInputStream(new File(oldPath)); fos = new FileOutputStream(newPath); bos=new BufferedOutputStream(fos); byte[] bytes=new byte[1024]; int len = 0; while ((len = fis.read(bytes))!= -1){ bos.write(bytes,0,len); } }finally { if (fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if (bos != null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
jdk1.7 try(){}自动关闭流:
public static void copyFileMethod(String oldPath,String newPath)throws Exception { int len = 0; //读取完毕自动关闭。。。。 byte[] bytes=new byte[1024]; try ( FileOutputStream fos = new FileOutputStream(new File(newPath)); BufferedOutputStream bos=new BufferedOutputStream(fos);){ try ( InputStream is = new FileInputStream(new File(oldPath)); BufferedInputStream bis=new BufferedInputStream(is)){ while ((len = bis.read(bytes)) != -1){ bos.write(bytes,0,len); } } } }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/260272.html