JAVA create files and folders to copy move

package com.java.ch151;

import java.io.File;
import java.io.IOException; //引入类

public class TextCreateFileAndDir { // 创建新文件和目录
     public static boolean createFile(String filePath) { // 创建单个文件
          File file = new File(filePath);
          if (file.exists()) { // 判断文件是否存在
               System.out.println("目标文件已存在" + filePath);
               return false;
          }
          if (filePath.endsWith(File.separator)) { // 判断文件是否为目录
               System.out.println("目标文件不能为目录!");
               return false;
          }
          // 判断目标文件所在的目录是否存在
          if (!file.getParentFile().exists()) { 
               // 如果目标文件所在的文件夹不存在,则创建父文件夹
               System.out.println("目标文件所在目录不存在,准备创建它!");
               if (!file.getParentFile().mkdirs()) { // 判断创建目录是否成功
                    System.out.println("创建目标文件所在的目录失败!");
                    return false;
               }
          }
          try {
               if (file.createNewFile()) { // 创建目标文件
                    System.out.println("创建文件成功:" + filePath);
                    return true;
               } else {
                    System.out.println("创建文件失败!");
                    return false;
               }
          } catch (IOException e) { // 捕获异常
               e.printStackTrace();
               System.out.println("创建文件失败!" + e.getMessage());
               return false;
          }
     }

     public static boolean createDir(String destDirName) {// 创建目录
          File dir = new File(destDirName);
          if (dir.exists()) { // 判断目录是否存在
               System.out.println("创建目录失败,目标目录已存在!");
               return false;
          }
          if (!destDirName.endsWith(File.separator)) { // 结尾是否以"/"结束
               destDirName = destDirName + File.separator;
          }
          if (dir.mkdirs()) { // 创建目标目录
               System.out.println("创建目录成功!" + destDirName);
               return true;
          } else {
               System.out.println("创建目录失败!");
               return false;
          }
     }

     public static String createTempFile(String prefix, String suffix,
               String dirName) { // 创建临时文件
          File tempFile = null;
          if (dirName == null) { // 目录如果为空
               try {
                    // 在默认文件夹下创建临时文件
                    tempFile = File.createTempFile(prefix, suffix);
                    return tempFile.getCanonicalPath(); // 返回临时文件的路径
               } catch (IOException e) { // 捕获异常
                    e.printStackTrace();
                    System.out.println("创建临时文件失败:" + e.getMessage());
                    return null;
               }
          } else { // 指定目录存在
               File dir = new File(dirName); // 创建目录
               if (!dir.exists()) { // 如果目录不存在则创建目录
                    if (TextCreateFileAndDir.createDir(dirName)) {
               System.out.println("创建临时文件失败,不能创建临时文件所在的目录!");
                         return null;
                    }
               }
               try {
                    // 在目录下创建临时文件
                    tempFile = File.createTempFile(prefix, suffix, dir);
                    return tempFile.getCanonicalPath(); // 返回临时文件的路径
               } catch (IOException e) { // 捕获异常
                    e.printStackTrace();
                    System.out.println("创建临时文件失败!" + e.getMessage());
                    return null;
               }
          }
     }

     public static void main(String[] args) {           // java程序的主入口处
          String dirName = "E:/createFile/";                // 创建目录
          TextCreateFileAndDir.createDir(dirName);      // 调用方法创建目录
          String fileName = dirName + "/file1.txt";      // 创建文件
          TextCreateFileAndDir.createFile(fileName);      // 调用方法创建文件
          String prefix = "temp";                          // 创建临时文件
          String surfix = ".txt";                          // 后缀
          for (int i = 0; i < 10; i++) {                     // 循环创建多个文件
               System.out.println("创建临时文件: "           // 调用方法创建临时文件
               + TextCreateFileAndDir.createTempFile(prefix, surfix,dirName));
          }
     }
}

The above procedure, createFile method creates a new file. First, determine whether the target file exists File through the method and isDirectory method exists for the file exists, it returns false, create a new file failed. If the target file does not exist, access to the target file by File method of getParentFile parent directory, if the parent directory does not exist, call the method File mkdirs create parent directory (if the parent directory parent directory does not exist, will create together), this time can determine the target file does not exist, and the parent directory already exists, use the file createNewFile method will be able to successfully create a new empty files.

Copy and move files and directories. Comprising moving a single file copy, copy the directory to the specified directory, together with copy subdirectories, files and subdirectories the directory and all copied. Specific code as follows:

import java.io.File; //引入类
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

//实现文件的简单处理,复制和移动文件、目录等
public class TextCopyFileAndMove { 
     // 移动指定文件夹内的全部文件
     public static void fileMove(String from, String to) throws Exception {
          try {
               File dir = new File(from);
               File[] files = dir.listFiles();      // 将文件或文件夹放入文件集
               if (files == null)                          // 判断文件集是否为空
                    return;
               File moveDir = new File(to);           // 创建目标目录
               if (!moveDir.exists()) {                // 判断目标目录是否存在
                    moveDir.mkdirs();                     // 不存在则创建
               }
               for (int i = 0; i < files.length; i++) {// 遍历文件集
                    // 如果是文件夹或目录,则递归调用fileMove方法,直到获得目录下的文件
                    if (files[i].isDirectory()) {
                         // 递归移动文件
                         fileMove(files[i].getPath(), to + "\\" + files[i].getName());
                         files[i].delete();                // 删除文件所在原目录
                    }
                    // 将文件目录放入移动后的目录
                    File moveFile = new File(moveDir.getPath() + "\\"
                              + files[i].getName());
                    if (moveFile.exists()) {           // 目标文件夹下存在的话,删除
                         moveFile.delete();
                    }
                    files[i].renameTo(moveFile);     // 移动文件
                    System.out.println(files[i] + " 移动成功");
               }
          } catch (Exception e) {
               throw e;
          }
     }
     // 复制目录下的文件(不包括该目录)到指定目录,会连同子目录一起复制过去。
     public static void copyFileFromDir(String toPath, String fromPath) {
          File file = new File(fromPath);
          createFile(toPath, false);                // true:创建文件 false创建目录
          if (file.isDirectory()) {                     // 如果是目录
               copyFileToDir(toPath, listFile(file));
          }
     }
     // 复制目录到指定目录,将目录以及目录下的文件和子目录全部复制到目标目录
     public static void copyDir(String toPath, String fromPath) {
          File targetFile = new File(toPath);      // 创建文件
          createFile(targetFile, false);                // 创建目录
          File file = new File(fromPath);           // 创建文件
          if (targetFile.isDirectory() && file.isDirectory()) { // 如果传入是目录
               copyFileToDir(targetFile.getAbsolutePath() + "/" + file.getName(),
                         listFile(file));                // 复制文件到指定目录
          }
     }
     // 复制一组文件到指定目录。targetDir是目标目录,filePath是需要复制的文件路径
     public static void copyFileToDir(String toDir, String[] filePath) {
          if (toDir == null || "".equals(toDir)) { // 目录路径为空
               System.out.println("参数错误,目标路径不能为空");
               return;
          }
          File targetFile = new File(toDir);
          if (!targetFile.exists()) {                // 如果指定目录不存在
               targetFile.mkdir();                     // 新建目录
          } else {
               if (!targetFile.isDirectory()) {      // 如果不是目录
                    System.out.println("参数错误,目标路径指向的不是一个目录!");
                    return;
               }
          }
          for (int i = 0; i < filePath.length; i++) { // 遍历需要复制的文件路径
               File file = new File(filePath[i]);      // 创建文件
               if (file.isDirectory()) {                // 判断是否是目录
                    // 递归调用方法获得目录下的文件
                    copyFileToDir(toDir + "/" + file.getName(), listFile(file));
                    System.out.println("复制文件 " + file);
               } else {
                    copyFileToDir(toDir, file, ""); // 文件到指定目录
               }
          }
     }
     // 复制文件到指定目录
     public static void copyFileToDir(String toDir, File file, String newName) {
          String newFile = "";
          if (newName != null && !"".equals(newName)) {
               newFile = toDir + "/" + newName;
          } else {
               newFile = toDir + "/" + file.getName();
          }
          File tFile = new File(newFile);
          copyFile(tFile, file);                          // 调用方法复制文件
     }
     public static void copyFile(File toFile, File fromFile) { // 复制文件
          if (toFile.exists()) {                          // 判断目标目录中文件是否存在
               System.out.println("文件" + toFile.getAbsolutePath() + "已经存在,跳过该文件!");
               return;
          } else {
               createFile(toFile, true);                // 创建文件
          }
          System.out.println("复制文件" + fromFile.getAbsolutePath() + "到"
                    + toFile.getAbsolutePath());
          try {                                              // 创建文件输入流
               InputStream is = new FileInputStream(fromFile);
               FileOutputStream fos = new FileOutputStream(toFile);// 文件输出流
               byte[] buffer = new byte[1024];      // 字节数组
               while (is.read(buffer) != -1) {      // 将文件内容写到文件中
                    fos.write(buffer);
               }
               is.close();                               // 输入流关闭
               fos.close();                               // 输出流关闭
          } catch (FileNotFoundException e) {      // 捕获文件不存在异常
               e.printStackTrace();
          } catch (IOException e) {                     // 捕获异常
               e.printStackTrace();
          }
     }
     public static String[] listFile(File dir) { // 获取文件绝对路径
          String absolutPath = dir.getAbsolutePath(); // 获取传入文件的路径
          String[] paths = dir.list();                // 文件名数组
          String[] files = new String[paths.length]; // 声明字符串数组,长为传入文件的个数
          for (int i = 0; i < paths.length; i++) { // 遍历显示文件绝对路径
               files[i] = absolutPath + "/" + paths[i];
          }
          return files;
     }
     public static void createFile(String path, boolean isFile) {// 创建文件或目录
          createFile(new File(path), isFile);      // 调用方法创建新文件或目录
     }
     public static void createFile(File file, boolean isFile) { // 创建文件
          if (!file.exists()) {                          // 如果文件不存在
               if (!file.getParentFile().exists()) { // 如果文件父目录不存在
                    createFile(file.getParentFile(), false);
               } else {                                    // 存在文件父目录
                    if (isFile) {                          // 创建文件
                         try {
                              file.createNewFile();      // 创建新文件
                         } catch (IOException e) {
                              e.printStackTrace();
                         }
                    } else {
                         file.mkdir();                     // 创建目录
                    }
               }
          }
     }
     public static void main(String[] args) {      // java程序主入口处
          String fromPath = "E:/createFile";           // 目录路径
          String toPath = "F:/createFile";           // 源路径
          System.out.println("1.移动文件:从路径 " + fromPath + " 移动到路径 " + toPath);
          try {
               fileMove(fromPath, toPath);           // 调用方法实现文件的移动
          } catch (Exception e) {
               System.out.println("移动文件出现问题" + e.getMessage());
          }
          System.out.println("2.复制目录 " + toPath + " 下的文件(不包括该目录)到指定目录" + fromPath
                    + " ,会连同子目录一起复制过去。");
          copyFileFromDir(fromPath, toPath);           // 调用方法实现目录复制
          System.out.println("3.复制目录 " + fromPath + "到指定目录 " + toPath
                    + " ,将目录以及目录下的文件和子目录全部复制到目标目录");
          // 调用方法实现目录以用目录下的文件和子目录全部复制
          copyDir(toPath, fromPath);
     }
}

Copy and move files and directories. Comprising moving a single file copy, copy the directory to the specified directory, together with copy subdirectories, files and subdirectories the directory and all copied. Specific code as follows:

package com.java.ch152;

import java.io.File; //引入类
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

//实现文件的简单处理,复制和移动文件、目录等
public class TextCopyFileAndMove { 
     // 移动指定文件夹内的全部文件
     public static void fileMove(String from, String to) throws Exception {
          try {
               File dir = new File(from);
               File[] files = dir.listFiles();      // 将文件或文件夹放入文件集
               if (files == null)                          // 判断文件集是否为空
                    return;
               File moveDir = new File(to);           // 创建目标目录
               if (!moveDir.exists()) {                // 判断目标目录是否存在
                    moveDir.mkdirs();                     // 不存在则创建
               }
               for (int i = 0; i < files.length; i++) {// 遍历文件集
                    // 如果是文件夹或目录,则递归调用fileMove方法,直到获得目录下的文件
                    if (files[i].isDirectory()) {
                         // 递归移动文件
                         fileMove(files[i].getPath(), to + "\\" + files[i].getName());
                         files[i].delete();                // 删除文件所在原目录
                    }
                    // 将文件目录放入移动后的目录
                    File moveFile = new File(moveDir.getPath() + "\\"
                              + files[i].getName());
                    if (moveFile.exists()) {           // 目标文件夹下存在的话,删除
                         moveFile.delete();
                    }
                    files[i].renameTo(moveFile);     // 移动文件
                    System.out.println(files[i] + " 移动成功");
               }
          } catch (Exception e) {
               throw e;
          }
     }
     // 复制目录下的文件(不包括该目录)到指定目录,会连同子目录一起复制过去。
     public static void copyFileFromDir(String toPath, String fromPath) {
          File file = new File(fromPath);
          createFile(toPath, false);                // true:创建文件 false创建目录
          if (file.isDirectory()) {                     // 如果是目录
               copyFileToDir(toPath, listFile(file));
          }
     }
     // 复制目录到指定目录,将目录以及目录下的文件和子目录全部复制到目标目录
     public static void copyDir(String toPath, String fromPath) {
          File targetFile = new File(toPath);      // 创建文件
          createFile(targetFile, false);                // 创建目录
          File file = new File(fromPath);           // 创建文件
          if (targetFile.isDirectory() && file.isDirectory()) { // 如果传入是目录
               copyFileToDir(targetFile.getAbsolutePath() + "/" + file.getName(),
                         listFile(file));                // 复制文件到指定目录
          }
     }
     // 复制一组文件到指定目录。targetDir是目标目录,filePath是需要复制的文件路径
     public static void copyFileToDir(String toDir, String[] filePath) {
          if (toDir == null || "".equals(toDir)) { // 目录路径为空
               System.out.println("参数错误,目标路径不能为空");
               return;
          }
          File targetFile = new File(toDir);
          if (!targetFile.exists()) {                // 如果指定目录不存在
               targetFile.mkdir();                     // 新建目录
          } else {
               if (!targetFile.isDirectory()) {      // 如果不是目录
                    System.out.println("参数错误,目标路径指向的不是一个目录!");
                    return;
               }
          }
          for (int i = 0; i < filePath.length; i++) { // 遍历需要复制的文件路径
               File file = new File(filePath[i]);      // 创建文件
               if (file.isDirectory()) {                // 判断是否是目录
                    // 递归调用方法获得目录下的文件
                    copyFileToDir(toDir + "/" + file.getName(), listFile(file));
                    System.out.println("复制文件 " + file);
               } else {
                    copyFileToDir(toDir, file, ""); // 文件到指定目录
               }
          }
     }
     // 复制文件到指定目录
     public static void copyFileToDir(String toDir, File file, String newName) {
          String newFile = "";
          if (newName != null && !"".equals(newName)) {
               newFile = toDir + "/" + newName;
          } else {
               newFile = toDir + "/" + file.getName();
          }
          File tFile = new File(newFile);
          copyFile(tFile, file);                          // 调用方法复制文件
     }
     public static void copyFile(File toFile, File fromFile) { // 复制文件
          if (toFile.exists()) {                          // 判断目标目录中文件是否存在
               System.out.println("文件" + toFile.getAbsolutePath() + "已经存在,跳过该文件!");
               return;
          } else {
               createFile(toFile, true);                // 创建文件
          }
          System.out.println("复制文件" + fromFile.getAbsolutePath() + "到"
                    + toFile.getAbsolutePath());
          try {                                              // 创建文件输入流
               InputStream is = new FileInputStream(fromFile);
               FileOutputStream fos = new FileOutputStream(toFile);// 文件输出流
               byte[] buffer = new byte[1024];      // 字节数组
               while (is.read(buffer) != -1) {      // 将文件内容写到文件中
                    fos.write(buffer);
               }
               is.close();                               // 输入流关闭
               fos.close();                               // 输出流关闭
          } catch (FileNotFoundException e) {      // 捕获文件不存在异常
               e.printStackTrace();
          } catch (IOException e) {                     // 捕获异常
               e.printStackTrace();
          }
     }
     public static String[] listFile(File dir) { // 获取文件绝对路径
          String absolutPath = dir.getAbsolutePath(); // 获取传入文件的路径
          String[] paths = dir.list();                // 文件名数组
          String[] files = new String[paths.length]; // 声明字符串数组,长为传入文件的个数
          for (int i = 0; i < paths.length; i++) { // 遍历显示文件绝对路径
               files[i] = absolutPath + "/" + paths[i];
          }
          return files;
     }
     public static void createFile(String path, boolean isFile) {// 创建文件或目录
          createFile(new File(path), isFile);      // 调用方法创建新文件或目录
     }
     public static void createFile(File file, boolean isFile) { // 创建文件
          if (!file.exists()) {                          // 如果文件不存在
               if (!file.getParentFile().exists()) { // 如果文件父目录不存在
                    createFile(file.getParentFile(), false);
               } else {                                    // 存在文件父目录
                    if (isFile) {                          // 创建文件
                         try {
                              file.createNewFile();      // 创建新文件
                         } catch (IOException e) {
                              e.printStackTrace();
                         }
                    } else {
                         file.mkdir();                     // 创建目录
                    }
               }
          }
     }
     public static void main(String[] args) {      // java程序主入口处
          String fromPath = "E:/createFile";           // 目录路径
          String toPath = "F:/createFile";           // 源路径
          System.out.println("1.移动文件:从路径 " + fromPath + " 移动到路径 " + toPath);
          try {
               fileMove(fromPath, toPath);           // 调用方法实现文件的移动
          } catch (Exception e) {
               System.out.println("移动文件出现问题" + e.getMessage());
          }
          System.out.println("2.复制目录 " + toPath + " 下的文件(不包括该目录)到指定目录" + fromPath
                    + " ,会连同子目录一起复制过去。");
          copyFileFromDir(fromPath, toPath);           // 调用方法实现目录复制
          System.out.println("3.复制目录 " + fromPath + "到指定目录 " + toPath
                    + " ,将目录以及目录下的文件和子目录全部复制到目标目录");
          // 调用方法实现目录以用目录下的文件和子目录全部复制
          copyDir(toPath, fromPath);
     }
}

In the above procedure, TextCopyFileAndMove class FileMove () method of moving all of the files in the specified folder. Create a file directory based on the incoming path to obtain files in the directory and sub-folders according to listFiles () method. Create a target directory and determines whether the target is present. Using the cycle will move files in the directory to the specified directory, if the cycle is derived using recursive folder access to documents in the folder, and then delete the original file's directory, the file is put into a specified directory. If the destination folder exists then delete the folder. The obtained file to a specified folder according renameTo () method.
copyFileFromDir () method to copy the files in the directory to the specified directory and subdirectories are copied along with the past, which is not included in the directory. Create a file from the specified directory object, call createFile () method creates a file object, because the second parameter passed is to create a directory to false, if the argument is true, the file is created. Create a file object according to the target path. If a directory is created, call the copyFileToDir () method copies the files in the specified directory to the target directory.
copyFileToDir () method to copy a set of files to a specified directory. Determine whether the specified directory is empty, if empty is returned. Create a file object according to the target path, if the file object does not exist, the directory object is new, otherwise the file to determine whether the object is a directory, if not a directory is returned. The use of loop through the file path you want to copy, create a corresponding file object according to the path, if the object is a file directory, call copyFileDir () method () method to copy files in the directory and files to a specified directory by listFile, if file directly copy the file to the directory.
copyFile () method is to copy files to a specified directory. exists File class () method to determine whether the specified file exists, if there is returned, otherwise call createFile () method to create the file. The incoming object files created input streams, and then create a file output stream according to the stream object, creating an array of bytes used to store data stream read. A data reading is not circulating is empty, write using a file output stream () method writes the contents of the target file to the specified file, read the associated stream resources released after completion.

listfile () method to obtain the file in the specified directory, and the absolute path of the file into a string array returned. File object list () method is to obtain files in a directory, use the absolute path to the directory in circulation file put string array returned.
whether createFile () method to determine the file exists, if it does not exist to determine parent directory of the file exists, if it does not exist call createFile () method to create the directory, or to determine whether the parent directory is a file, if the file you create a new file otherwise, create a directory.
Run results are shown below.
1. Mobile file: from the path E: / createFile moved to the path F.: / CreateFile
E: \ CreateFile \ file1.txt moved successfully
E: \ createFile \ temp1 \ file1.txt moved successfully
E: \ createFile \ temp1 successfully moved
E: \ createFile \ temp26661.txt moved successfully
E: \ createFile \ temp26662.txt successfully moved
......
2. copy the directory F: / files in createFile (not including the directory) to the specified directory E: / createFile, will together with subdirectories copy the past.
Copy the file F: \ createFile \ createFile \ file1.txt to E: \ createFile \ createFile \ file1.txt
copy the file F: \ createFile \ createFile \ temp1 \ file1.txt to E: \ createFile \ createFile \ temp1 \ file1.txt
copy the file F: \ createFile \ createFile \ temp1
Copy the file F: \ createFile \ createFile \ temp26661.txt to E: \ CreateFile \ CreateFile \ temp26661.txt
......
3. Copy the directory E: / createFile to the specified directory F: / createFile, the files and subdirectories in the directory and directory copy all to the target directory
to copy the file E: \ createFile \ createFile \ file1.txt to F: \ createFile \ createFile \ createFile \ file1.txt
copy the file E: \ createFile \ createFile \ temp1
copy the file E: \ createFile \ createFile
file F : \ createFile \ createFile \ file1.txt already exists, skip the file!
File F: \ createFile \ createFile \ temp1 \ file1.txt already exists, skip the file!
File F: \ createFile \ createFile \ temp26661.txt already exists, skip the file!
......

Published 18 original articles · won praise 16 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_44569012/article/details/90707966