版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/skymouse2002/article/details/80546622
第一种使用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();
}