public static void copy(File src, File dst) { try { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; while (in.read(buffer) > 0) { out.write(buffer); } } finally { if (null != in) { in.close(); } if (null != out) { out.close(); } } } catch (Exception e) { e.printStackTrace(); } } public static void copyFile(File sourceFile, File targetFile) { BufferedInputStream inBuff = null; BufferedOutputStream outBuff = null; try { inBuff = new BufferedInputStream(new FileInputStream(sourceFile)); outBuff = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] b = new byte[1024 * 1024]; int len; while ((len = inBuff.read(b)) != -1) { outBuff.write(b, 0, len); } outBuff.flush(); } catch (Exception e) { } finally { if (inBuff != null) try { inBuff.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (outBuff != null) try { outBuff.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static String generateFileName(String fileName) { String formatDate = new SimpleDateFormat("yyMMddHHmmss") .format(new Date()); int random = new Random().nextInt(10000); int position = fileName.lastIndexOf("."); String extension = fileName.substring(position); return formatDate + random + extension; }
时间: 2024-01-05 20:04:26 浏览: 64
这段代码实现了文件的复制和生成新的文件名。首先是一个copy方法,使用了InputStream和OutputStream来读取和写入文件,使用了缓冲区来提高读写效率。接着是一个copyFile方法,使用了BufferedInputStream和BufferedOutputStream来读取和写入文件,并且设置了缓冲区的大小为1MB。最后是一个generateFileName方法,通过获取当前时间和一个随机数来生成一个新的文件名,保证了文件名的唯一性。值得注意的是,这些方法中都有异常处理机制,确保了程序的稳定性。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)