本文共 1299 字,大约阅读时间需要 4 分钟。
第一种使用FileInputstream读取,使用FileOutputStream写入到文件中
FileInputStream input = null; FileOutputStream output = null; String path="D:\\java\\"; String fileName="test.txt"; String newFilename=System.currentTimeMillis()+".txt"; try { input = new FileInputStream(new File(path+fileName)); output = new FileOutputStream(new File(path+newFilename)); byte[] bt = new byte[1024]; int realbyte = 0; while((realbyte=input.read(bt))>0){ output.write(bt, 0, realbyte); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (input != null) { input.close(); } if (output != null) { output.close(); } } catch (IOException e) { e.printStackTrace(); } }
下面是try-with-resource模式,这种模式中对应类的接口要实现java.lang.AutoCloseable接口或者它的继承者java.io.Closeable接口,而FileInputStream 对应的抽象类InputStream就实现了java.io.Closeable接口。
String path="D:\\java\\"; String fileName="test.txt"; String newFilename=System.currentTimeMillis()+".txt"; try ( FileInputStream input = new FileInputStream(new File(path+fileName)); FileOutputStream output = new FileOutputStream(new File(path+newFilename))) { byte[] bt = new byte[1024]; int realbyte = 0; while((realbyte=input.read(bt))>0){ output.write(bt, 0, realbyte); } }catch (Exception e) { e.printStackTrace(); }
转载地址:http://uwtsi.baihongyu.com/