栏目:IO与序列化 作者:admin 日期:2015-08-11 评论:0 点击: 4,923 次
在上篇文章里,《深入解析FileInputStream和FileOutputStream》,有个疑问:如何才能更高效的读写文件呢?这个疑问将在本文中得到答案:在进行文件读写的时候,最好是使用带缓存的BufferedInputStream和BufferedOutputStream类。通过下面的一个小例子,大家可以看看BufferedInputStream和BufferedOutputStream是怎么使用的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
public class Test { private final static int BUFFER_SIZE = 16 * 1024; public static void main(String[] args) { File src = new File("d:\\src.txt"); File dst = new File("d:\\dst.txt"); doSaveFile(src, dst); } public static void doSaveFile(File src, File dst) { 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]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (Exception e) { } finally { if (null != in) { try { in.close(); } catch (IOException e) { } } if (null != out) { try { out.close(); } catch (IOException e) { } } } } } |
------====== 本站公告 ======------
金丝燕网,一个严谨的网站!