JAVA 如何创建/删除/修改/复制目录及文件 3in1

  这需要导入java.io类
import java.io.*;

public class FileOperate {
  public FileOperate() {
  }

  /**
   * 新建目录
   * @param folderPath String 如 c:/fqf
   * @return boolean
   */
  public void newFolder(String folderPath) {
    try {
      String filePath = folderPath;
      filePath = filePath.toString();
      java.io.File myFilePath = new java.io.File(filePath);
      if (!myFilePath.exists()) {
        myFilePath.mkdir();
      }
    }
    catch (Exception e) {
      System.out.println("新建目录操作出错");
      e.printStackTrace();
    }
  }

  /**
   * 新建文件
   * @param filePathAndName String 文件路径及名称 如c:/fqf.txt
   * @param fileContent String 文件内容
   * @return boolean
   */
  public void newFile(String filePathAndName, String fileContent) {

    try {
      String filePath = filePathAndName;
      filePath = filePath.toString();
      File myFilePath = new File(filePath);
      if (!myFilePath.exists()) {
        myFilePath.createNewFile();
      }
      FileWriter resultFile = new FileWriter(myFilePath);
      PrintWriter myFile = new PrintWriter(resultFile);
      String strContent = fileContent;
      myFile.println(strContent);
      resultFile.close();

    }
    catch (Exception e) {
      System.out.println("新建目录操作出错");
      e.printStackTrace();

    }

  }

  /**
   * 删除文件
   * @param filePathAndName String 文件路径及名称 如c:/fqf.txt
   * @param fileContent String
   * @return boolean
   */
  public void delFile(String filePathAndName) {
    try {
      String filePath = filePathAndName;
      filePath = filePath.toString();
      java.io.File myDelFile = new java.io.File(filePath);
      myDelFile.delete();

    }
    catch (Exception e) {
      System.out.println("删除文件操作出错");
      e.printStackTrace();

    }

  }

  /**
   * 删除文件夹
   * @param filePathAndName String 文件夹路径及名称 如c:/fqf
   * @param fileContent String
   * @return boolean
   */
  public void delFolder(String folderPath) {
    try {
      delAllFile(folderPath); //删除完里面所有内容
      String filePath = folderPath;
      filePath = filePath.toString();
      java.io.File myFilePath = new java.io.File(filePath);
      myFilePath.delete(); //删除空文件夹

    }
    catch (Exception e) {
      System.out.println("删除文件夹操作出错");
      e.printStackTrace();

    }

  }

  /**
   * 删除文件夹里面的所有文件
   * @param path String 文件夹路径 如 c:/fqf
   */
  public void delAllFile(String path) {
    File file = new File(path);
    if (!file.exists()) {
      return;
    }
    if (!file.isDirectory()) {
      return;
    }
    String[] tempList = file.list();
    File temp = null;
    for (int i = 0; i < tempList.length; i++) {
      if (path.endsWith(File.separator)) {
        temp = new File(path + tempList[i]);
      }
      else {
        temp = new File(path + File.separator + tempList[i]);
      }
      if (temp.isFile()) {
        temp.delete();
      }
      if (temp.isDirectory()) {
        delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
        delFolder(path+"/"+ tempList[i]);//再删除空文件夹
      }
    }
  }

  /**
   * 复制单个文件
   * @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); //读入原文件
        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();

    }

  }

  /**
   * 移动文件到指定目录
   * @param oldPath String 如:c:/fqf.txt
   * @param newPath String 如:d:/fqf.txt
   */
  public void moveFile(String oldPath, String newPath) {
    copyFile(oldPath, newPath);
    delFile(oldPath);

  }

  /**
   * 移动文件到指定目录
   * @param oldPath String 如:c:/fqf.txt
   * @param newPath String 如:d:/fqf.txt
   */
  public void moveFolder(String oldPath, String newPath) {
    copyFolder(oldPath, newPath);
    delFolder(oldPath);

  }
}



java中删除目录事先要删除目录下的文件或子目录。用递归就可以实现。这是我第一个用到算法作的程序,哎看来没白学。
public void del(String filepath) throws IOException{
File f = new File(filepath);//定义文件路径       
if(f.exists() && f.isDirectory()){//判断是文件还是目录
    if(f.listFiles().length==0){//若目录下没有文件则直接删除
        f.delete();
    }else{//若有则把文件放进数组,并判断是否有下级目录
        File delFile[]=f.listFiles();
        int i =f.listFiles().length;
        for(int j=0;j<i;j++){
            if (delFile[j].isDirectory()){                                                del (delFile[j].getAbsolutePath());//递归调用del方法并取得子目录路径
            }
            delFile[j].delete();//删除文件
        }
    }
    del(filepath);//递归调用
}

}    


删除一个非空目录并不是简单地创建一个文件对象,然后再调用delete()就可以完成的。要在平台无关的方式下安全地删除一个非空目录,你还需要一个算法。该算法首先删除文件,然后再从目录树的底部由下至上地删除其中所有的目录。

只要简单地在目录中循环查找文件,再调用delete就可以清除目录中的所有文件:

static public void emptyDirectory(File directory) {
   File[ ] entries = directory.listFiles( );
   for(int i=0; i<entries.length; i++) {
       entries[i].delete( );
   }
}
这个简单的方法也可以用来删除整个目录结构。当在循环中遇到一个目录时它就递归调用deleteDirectory,而且它也会检查传入的参数是否是一个真正的目录。最后,它将删除作为参数传入的整个目录。
static public void deleteDirectory(File dir) throws IOException {
   if( (dir == null) || !dir.isDirectory) {
       throw new IllegalArgumentException(

                 "Argument "+dir+" is not a directory. "
             );
   }

   File[ ] entries = dir.listFiles( );
   int sz = entries.length;

   for(int i=0; i<sz; i++) {
       if(entries[i].isDirectory( )) {
           deleteDirectory(entries[i]);
       } else {
           entries[i].delete( );
       }
   }

  dir.delete();
}
在Java 1.1以及一些J2ME/PersonalJava的变种中没有File.listFiles方法。所以只能用File.list,它的返回值一个字符串数组,你要为每个字符串构造一个新的文件对象。 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 下面是一个简单的 Java 程序,可以实现文本文件的读入、复制、查询和修改。 首先,我们需要导入以下几个类: ``` import java.io.*; import java.util.Scanner; ``` 然后,我们可以使用 `File` 类来打开文本文件,并使用 `Scanner` 类来读取文件中的内容。 ``` File inputFile = new File("input.txt"); Scanner sc = new Scanner(inputFile); ``` 接下来,我们可以使用 `sc.nextLine()` 方法来读取文件中的每一行,并使用 `System.out.println()` 方法来输出内容。 ``` while (sc.hasNextLine()) { String line = sc.nextLine(); System.out.println(line); } ``` 如果要复制文本文件,可以使用 `FileInputStream` 和 `FileOutputStream` 类,将文件的内容读取到内存中,再写入到另一个文件中。 ``` FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.close(); ``` 如果要查询文件中的某一行,可以使用 `indexOf()` 方法来查找该行的位置。 ``` int index = 0; while (sc.hasNextLine()) { String line = sc.nextLine(); if (line.contains("search string")) { System.out.println("Line found at index: " + index); break; } index++; } ``` 如果要修改文件中的某一行,可以先读取整个文件的内容到内存中,然后修改相应的行,最后再将修改后的内容写回 ### 回答2: Java是一种面向对象的编程语言,非常适合用来开发程序。下面是一个使用Java编写的可以实现文本文件的读入、复制、查询和修改功能的程序: ```java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class FileManipulator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入要读取的文件路径:"); String filePath = scanner.nextLine(); // 读取文件内容 String fileContent = readFile(filePath); System.out.println("文件内容为:"); System.out.println(fileContent); System.out.print("请输入要复制到的位置:"); String copyPath = scanner.nextLine(); // 复制文件 boolean isCopied = copyFile(filePath, copyPath); if (isCopied) { System.out.println("文件复制成功!"); } else { System.out.println("文件复制失败!"); } System.out.print("请输入要查询的关键字:"); String keyword = scanner.nextLine(); // 查询文件是否包含关键字 boolean containsKeyword = containsKeyword(filePath, keyword); if (containsKeyword) { System.out.println("文件包含关键字:" + keyword); } else { System.out.println("文件不包含关键字:" + keyword); } System.out.print("请输入要修改的关键字:"); String oldKeyword = scanner.nextLine(); System.out.print("请输入修改后的关键字:"); String newKeyword = scanner.nextLine(); // 修改文件中的关键字 boolean isModified = modifyKeyword(filePath, oldKeyword, newKeyword); if (isModified) { System.out.println("文件修改成功!"); } else { System.out.println("文件修改失败!"); } } // 读取文件内容 public static String readFile(String filePath) { StringBuilder content = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } } catch (IOException e) { e.printStackTrace(); } return content.toString(); } // 复制文件 public static boolean copyFile(String sourcePath, String destinationPath) { try (BufferedReader reader = new BufferedReader(new FileReader(sourcePath)); BufferedWriter writer = new BufferedWriter(new FileWriter(destinationPath))) { String line; while ((line = reader.readLine()) != null) { writer.write(line); writer.newLine(); } return true; } catch (IOException e) { e.printStackTrace(); return false; } } // 查询文件是否包含关键字 public static boolean containsKeyword(String filePath, String keyword) { try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; while ((line = reader.readLine()) != null) { if (line.contains(keyword)) { return true; } } } catch (IOException e) { e.printStackTrace(); } return false; } // 修改文件中的关键字 public static boolean modifyKeyword(String filePath, String oldKeyword, String newKeyword) { try (BufferedReader reader = new BufferedReader(new FileReader(filePath)); BufferedWriter writer = new BufferedWriter(new FileWriter(filePath + ".tmp"))) { String line; while ((line = reader.readLine()) != null) { line = line.replace(oldKeyword, newKeyword); writer.write(line); writer.newLine(); } } catch (IOException e) { e.printStackTrace(); return false; } // 删除原始文件,将临时文件重命名为原始文件名 try { java.io.File oldFile = new java.io.File(filePath); java.io.File newFile = new java.io.File(filePath + ".tmp"); if (oldFile.delete()) { newFile.renameTo(oldFile); return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } } } ``` 这个程序使用BufferedReader和BufferedWriter来读取和写入文件内容。readFile函数用于读取文件内容并返回字符串形式的内容。copyFile函数将源文件复制到目标位置。containsKeyword函数用于确定文件是否包含给定的关键字。modifyKeyword函数用于修改文件中的关键字,它会创建一个临时文件来写入修改后的内容,并在修改完成后将临时文件重命名为原始文件名。 请在运行程序时按照程序提示依次输入文件路径、复制目标位置、查询关键字、修改前关键字和修改后关键字。程序会根据输入进行相应操作,并输出相应的结果。 ### 回答3: Java是一种面向对象的编程语言,可以轻松地编写一个可以实现文本文件的读入、复制、查询和修改的程序。 首先,我们需要使用Java文件输入输出库来读取文本文件。可以使用 java.io 包提供的 FileReader 和 BufferedReader 类。我们可以通过使用这些类来逐行读取文本文件的内容,并将其存储在一个字符串变量中。 接下来是复制操作。可以使用 java.io 包提供的 FileWriter 和 BufferedWriter 类来创建一个新的文件,并将读取到的内容写入到这个新文件中。 对于查询操作,我们可以使用正则表达式来搜索文本文件中的特定内容。Java中的 Pattern 和 Matcher 类提供了强大的支持。我们可以使用 Pattern 类来创建一个正则表达式模式,并使用 Matcher 类来在文本文件中执行匹配操作。 最后是修改操作。可以使用 java.io 包提供的 FileWriter 和 BufferedWriter 类来覆盖原始文件的内容。我们可以将修改后的内容写入到原始文件中,从而实现对文件修改。 这就是用Java编写实现文本文件读取、复制、查询和修改的程序的基本思路。当然,在实际的开发过程中可能会涉及到更多的问题和细节,但是基本的步骤是相通的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值