java复制文件的4种方式及拷贝文件到另一个目录下与删除单个文件和删除整个文件夹

1.使用FileStreams复制

这是最经典的方式将一个文件的内容复制到另一个文件中。 使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件B。 这是第一个方法的代码:

private static void copyFileUsingFileStreams(File source, File dest) 
    throws IOException {
    
       
  InputStream input = null;   
  OutputStream output = null;   
  try {
    
     
      input = new FileInputStream(source); 
      output = new FileOutputStream(dest);     
      byte[] buf = new byte[1024];     
      int bytesRead;     
      while ((bytesRead = input.read(buf)) > 0) {
    
     
        output.write(buf, 0, bytesRead); 
      } 
  } finally {
    
     
    input.close(); 
    output.close(); 
  } 
} 

正如你所看到的我们执行几个读和写操作try的数据,所以这应该是一个低效率的,下一个方法我们将看到新的方式。

2.使用FileChannel复制

Java NIO包括transferFrom方法,根据文档应该比文件流复制的速度更快

private static void copyFileUsingFileChannels(File source, File dest) throws IOException {
    
       
    FileChannel inputChannel = null;   
    FileChannel outputChannel = null;   
  try {
    
     
    inputChannel = new FileInputStream(source).getChannel(); 
    outputChannel = new FileOutputStream(dest).getChannel(); 
    outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); 
  } finally {
    
     
    inputChannel.close(); 
    outputChannel.close(); 
  } 
} 

3.使用Commons IO复制

Apache Commons IO提供拷贝文件方法在其FileUtils类,可用于复制一个文件到另一个地方。它非常方便使用Apache Commons FileUtils类时,您已经使用您的项目。基本上,这个类使用Java NIO FileChannel内部。 这是第三种方法的代码:

private static void copyFileUsingApacheCommonsIO(File source, File dest) 
    throws IOException {
    
     
  FileUtils.copyFile(source, dest); 
} 

4.使用Java7的Files类复制

如果你有一些经验在Java 7中你可能会知道,可以使用复制方法的Files类文件,从一个文件复制到另一个文件。 这是第四个方法的代码:

private static void copyFileUsingJava7Files(File source, File dest) 
    throws IOException {
    
       
    Files.copy(source.toPath(), dest.toPath()); 
}

5.下面看下java拷贝文件到另一个目录下的实现代码,具体代码如下所示

public class FileUtils {
    
    
/** 
* 复制单个文件 
* @param oldPath String 原文件路径 如:c:/fqf.txt 
* @param newPath String 复制后路径 如:f:/fqf.txt 
* @return boolean 
*/ 
public void copyFile(String oldPath, String newPath) {
    
     
try {
    
     
int bytesum = 0; 
int byteread = 0; 
File oldfile = new File(oldPath); 
if (oldfile.exists()) {
    
     //文件存在时 
InputStream inStream = new FileInputStream(oldPath); //读入原文件 
String folderPath = newPath.substring(0, newPath.indexOf("/"));
File folder = new File(folderPath);
if (!folder.exists() && !folder.isDirectory()) {
    
    
    folder.mkdirs();
}
FileOutputStream fs = new FileOutputStream(newPath); 
byte[] buffer = new byte[1444]; 
int length; 
while ( (byteread = inStream.read(buffer)) != -1) {
    
     
bytesum += byteread; //字节数 文件大小 
System.out.println(bytesum); 
fs.write(buffer, 0, byteread); 
} 
inStream.close(); 
} 
} 
catch (Exception e) {
    
     
System.out.println("复制单个文件操作出错"); 
e.printStackTrace();
}
}
/** 
* 复制整个文件夹内容 
* @param oldPath String 原文件路径 如:c:/fqf 
* @param newPath String 复制后路径 如:f:/fqf/ff 
* @return boolean 
*/ 
public void copyFolder(String oldPath, String newPath) {
    
    
try {
    
     
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹 
File a=new File(oldPath); 
String[] file=a.list(); 
File temp=null; 
for (int i = 0; i < file.length; i++) {
    
     
if(oldPath.endsWith(File.separator)){
    
     
temp=new File(oldPath+file[i]); 
} 
else{
    
     
temp=new File(oldPath+File.separator+file[i]); 
}
if(temp.isFile()){
    
     
FileInputStream input = new FileInputStream(temp); 
FileOutputStream output = new FileOutputStream(newPath + "/" + 
(temp.getName()).toString()); 
byte[] b = new byte[1024 * 5]; 
int len; 
while ( (len = input.read(b)) != -1) {
    
     
output.write(b, 0, len); 
} 
output.flush(); 
output.close(); 
input.close(); 
} 
if(temp.isDirectory()){
    
    //如果是子文件夹 
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]); 
} 
} 
} 
catch (Exception e) {
    
     
System.out.println("复制整个文件夹内容操作出错"); 
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception {
    
    
// //这是你的源文件,本身是存在的
// File beforefile = new File("C:/Users/Administrator/Desktop/Untitled-2.html");
//
// //这是你要保存之后的文件,是自定义的,本身不存在
// File afterfile = new File("C:/Users/Administrator/Desktop/jiekou0/Untitled-2.html");
//
// //定义文件输入流,用来读取beforefile文件
// FileInputStream fis = new FileInputStream(beforefile);
//
// //定义文件输出流,用来把信息写入afterfile文件中
// FileOutputStream fos = new FileOutputStream(afterfile);
//
// //文件缓存区
// byte[] b = new byte[1024];
// //将文件流信息读取文件缓存区,如果读取结果不为-1就代表文件没有读取完毕,反之已经读取完毕
// while(fis.read(b)!=-1){
    
    
// //将缓存区中的内容写到afterfile文件中
// fos.write(b);
// fos.flush();
// }
String oldPath="C:/Users/Administrator/Desktop/Untitled-2.html";
String newPath="C:/Users/Administrator/Desktop/jiekou0/Untitled-2.html";
FileUtils t=new FileUtils ();
t.copyFile(oldPath, newPath);
}
}

6.删除单个文件

/**
     * 删除单个文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath)
    {
    
    
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists())
        {
    
    
            file.delete();
            flag = true;
        }
        return flag;
    }

7.递归删除整个文件夹

/**
     * 删除指定文件夹下的全部内容
     * @param file
     */
    public static void deleteAll(File file) {
    
    
        File[] files = file.listFiles();//将file子目录及子文件放进文件数组
        if (files != null) {
    
    //如果包含文件进行删除操作
            for (int i = 0; i < files.length; i++) {
    
    
                if (files[i].isFile()) {
    
    //删除子文件
                    files[i].delete();
                } else if (files[i].isDirectory()) {
    
    //通过递归方法删除子目录的文件
                    deleteAll(files[i]);
                }
                files[i].delete();//删除子目录
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_43684214/article/details/127284989