java中文件的复制

第一种:使用Java7的Files类复制

                        File dd=new File("D:/Tomcat7.0/webapps/ROOT1523957275296.xml");
File dd2=new File("D:/Tomcat7.0/webapps/333.xml");

Files.copy(dd.toPath(),dd2.toPath());

第二种:使用Commons IO复制

                        File dd=new File("D:/Tomcat7.0/webapps/ROOT1523957275296.xml");
File dd2=new File("D:/Tomcat7.0/webapps/333.xml");
FileUtils.copyFile(dd, dd2);

第三种:使用FileChannel复制

                        File dd=new File("D:/Tomcat7.0/webapps/config.xml");
File dd2=new File("D:/Tomcat7.0/webapps/444.xml");
FileChannel inputStream=null;
     FileChannel outStream=null;
     try {
inputStream = new FileInputStream(dd).getChannel();
outStream=new FileOutputStream(dd2).getChannel();
outStream.transferFrom(inputStream, 0, inputStream.size());
} catch (Exception e) {
e.printStackTrace();
}finally{
if(null!=outStream){
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null!=inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

第四种:使用BufferedReader复制

                        File dd=new File("D:/Tomcat7.0/webapps/config.xml");
File dd2=new File("D:/Tomcat7.0/webapps/44.xml");
BufferedReader br=null;
BufferedWriter bw=null;
try {
br=new BufferedReader(new FileReader(dd));
bw=new BufferedWriter(new FileWriter(dd2));
String line=null;
while((line=br.readLine())!=null){
bw.write(line+"\n");
}
bw.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(null!=bw){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null!=br){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

第五种:使用FileStreams复制

扫描二维码关注公众号,回复: 177195 查看本文章

                        File dd=new File("D:/Tomcat7.0/webapps/config.xml");
File dd2=new File("D:/Tomcat7.0/webapps/555.xml");
InputStream iputStream=null;
OutputStream outStream=null;
try {
iputStream=new FileInputStream(dd);
outStream = new FileOutputStream(dd2);
byte[] byteData=new byte[1024];
int byteRead=0;
while((byteRead=iputStream.read(byteData))>0){
outStream.write(byteData, 0, byteRead);
}
outStream.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(null!=outStream){
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null!=iputStream){
try {
iputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


猜你喜欢

转载自blog.csdn.net/jingyang07/article/details/79984450