file 操作

来源:互联网 发布:魔法医生黑金面膜 知乎 编辑:程序博客网 时间:2024/05/16 10:31

Java文件操作我个人认为重要的问题有:

  a:如何跨平台问题
  b:文件编码问题,尤其是多语言平台情况下如何正常工作。
  c:文件读写效率、操作效率
  d:文件加密和文件安全
  e:文件快速检索,强烈建议使用lence进行文件检索及文件管理。

以下是本人做的一些整理:

一:建立文件

Java代码 复制代码
  1. File file1 = new File ("C://temp//myNote.txt"); // in Windows  这是windows文件系统下的方法   
  2. File file2 = new File ("/tmp/myNote.txt"); // in Linux/Unix        unix文件系统的方法  

 



最安全的建立文件的方法:

Java代码 复制代码
  1. File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");   
  2.   
  3.    //File.separator 是文件路径符号。   
  4.   System.out.println(myFile.getName());//取得文件名称的方法   
  5.   System.out.println(myFile.getPath());//取得文件路径的方法   
  6.   System.out.println(myFile.isAbsolute());//判断文件是否完整   
  7.   System.out.println(myFile.getParent());//取得文件的根目录   
  8.   System.out.println(myFile.exists());//判断文件是否存在   
  9.   System.out.println(myFile.isDirectory());//判断是否是目录   
  10.   System.out.println(myFile.isFile());//判断是否是文件   
  11.   System.out.println(myFile.isHidden());//判断是否是隐藏文件   
  12.   System.out.println(myFile.canRead());//判断是否可读   
  13.   System.out.println(myFile.canWrite());//判断是否可写   
  14.   
  15.   File myFile_A = new File("C:" + File.separator);   
  16.        for(String s: myFile_A.list()){//读取某个目录下所有文件   
  17.        System.out.println(s);   
  18.        }   
  19.   
  20.     File myFile_C=new File("d:/test.txt");   
  21.            System.out.println(new Date(myFile_C.lastModified()));//最后一次编辑时间   
  22.        myFile_C.renameTo(new File("c:/text.txt.bak"));//从命名   
  23.        myFile_C.setReadOnly();//设置为只读  

 

二:文件过滤方法

   java提供了很好的文件过滤借口:FilenameFilter 过滤以后的文件可以用listFiles显示出来。效率还是非常高的。

Java代码 复制代码
  1. import java.io.File;   
  2. import java.io.FilenameFilter;   
  3. import java.util.Date;   
  4. /**  
  5. * 文件过滤器过滤类  
  6. * @author fb  
  7. */  
  8. class FileListFilter implements FilenameFilter {   
  9.  private String name;   
  10.  private String extension;   
  11.  public FileListFilter(String name, String extension) {   
  12.    this.name = name;   
  13.    this.extension = extension;   
  14.  }   
  15.  public boolean accept(File directory, String filename) {   
  16.    boolean fileOK = true;   
  17.    if (name != null) {   
  18.      fileOK = filename.startsWith(name);   
  19.    }   
  20.    if (extension != null) {   
  21.      fileOK = filename.endsWith('.' + extension);   
  22.    }   
  23.    return fileOK;   
  24.  }   
  25. }  

 


测试方法:

Java代码 复制代码
  1. import java.io.File;   
  2. import java.io.FilenameFilter;   
  3. import java.util.Date;   
  4. /**  
  5. * 文件过滤器   运行函数  
  6. * @author fb  
  7. */  
  8. public class Run_FileListFilter {   
  9.  public static void main(String[] args) {   
  10.      File myDir = new File("d:/");   
  11.      FilenameFilter select = new FileListFilter("F""txt");   
  12.      File[] contents = myDir.listFiles(select);   
  13.      for (File file : contents) {   
  14.        System.out.println(file + " is a " + (file.isDirectory() ? "directory" : "file")   
  15.            + " last modified on/n" + new Date(file.lastModified()));   
  16.      }   
  17.  }   
  18. }  

 


三:建立目录、文件、临时文件、删除文件或目录

Java代码 复制代码
  1. import java.io.File;   
  2. import java.io.IOException;   
  3.   
  4. public class MakeDir {   
  5.     
  6.  public static void main(String[] args) {   
  7.    File myFile=new File("D:/myFubin/");   
  8.    if(myFile.mkdir()){//单级目录   
  9.      System.out.println("建立目录成功");   
  10.    }else{   
  11.      System.out.println("建立目录失败");   
  12.    }   
  13.       
  14.    File myFile_A=new File("D:/myFubin/test/");   
  15.    if(myFile_A.mkdirs()){//多级目录   
  16.      System.out.println("建立目录成功");   
  17.    }else{   
  18.      System.out.println("建立目录失败");   
  19.    }   
  20.       
  21.    File file = new File("d://myFubin//test.txt");   
  22.    try {   
  23.      file.createNewFile();//建立空文件   
  24.    } catch (IOException e) {   
  25.      e.printStackTrace();   
  26.    }   
  27.       
  28.    System.out.println(file.canRead());   
  29.       
  30.    if(file.delete()){//删除文件或删除目录   
  31.      //删除文件的另外一个方法:file.deleteOnExit() 这种方法是在程序退出的时候将文件删除   
  32.      System.out.println("删除成功");   
  33.    }else{   
  34.      System.out.println("删除失败");   
  35.    }     
  36.       
  37.    try {   
  38.      File  tmp = File.createTempFile("foo""tmp");//建立临时文件   
  39.      System.out.println("刚才建立的临时文件在:" + tmp.getCanonicalPath());   
  40.    } catch (IOException e) {   
  41.      e.printStackTrace();   
  42.    }   
  43.       
  44.       
  45.  }   
  46.     
  47. }  

 

 

Java代码 复制代码
  1. import java.io.File;   
  2. /**  
  3. * @author fb  www.cujava.com  
  4. * 文件操作里Java 1.6 新功能:查询磁盘空间  
  5. */  
  6. public class SpaceChecker {   
  7.   
  8.   public static void main(String[] args) {   
  9.   File[] roots = File.listRoots();//取得所有的根,如果是windows系统那么将取得所有的磁盘   
  10.       for (int i = 0; i < roots.length; i++) {   
  11.         System.out.println(roots[i]);   
  12.         System.out.println("Free space = " + roots[i].getFreeSpace());   
  13.         System.out.println("Usable space = " + roots[i].getUsableSpace());   
  14.         System.out.println("Total space = " + roots[i].getTotalSpace());   
  15.         System.out.println();   
  16.       }   
  17.   }   
  18. }   

 

 

JAVA文件操作类和文件夹的操作代码实例,包括读取文本文件内容, 新建目录,多级目录创建,新建文件,有编码方式的文件创建, 删除文件,删除文件夹,删除指定文件夹下所有文件, 复制单个文件,复制整个文件夹的内容,移动文件,移动目录等

 

Java代码 复制代码
  1. /**  
  2.      * 读取文本文件内容  
  3.      * @param filePathAndName 带有完整绝对路径的文件名  
  4.      * @param encoding 文本文件打开的编码方式  
  5.      * @return 返回文本文件的内容  
  6.      */  
  7.     public String readTxt(String filePathAndName, String encoding)   
  8.         throws IOException {   
  9.         encoding = encoding.trim();   
  10.         StringBuffer str = new StringBuffer("");   
  11.         String st = "";   
  12.         try {   
  13.             FileInputStream fs = new FileInputStream(filePathAndName);   
  14.             InputStreamReader isr;   
  15.             if (encoding.equals("")) {   
  16.                 isr = new InputStreamReader(fs);   
  17.             } else {   
  18.                 isr = new InputStreamReader(fs, encoding);   
  19.             }   
  20.             BufferedReader br = new BufferedReader(isr);   
  21.             try {   
  22.                 String data = "";   
  23.                 while ((data = br.readLine()) != null) {   
  24.                     str.append(data + " ");   
  25.                 }   
  26.             } catch (Exception e) {   
  27.                 str.append(e.toString());   
  28.             }   
  29.             st = str.toString();   
  30.         } catch (IOException es) {   
  31.             st = "";   
  32.         }   
  33.         return st;   
  34.     }  

 

Java代码 复制代码
  1. /**  
  2.     * 新建目录  
  3.     * @param folderPath 目录  
  4.     * @return 返回目录创建后的路径  
  5.     */  
  6.    public String createFolder(String folderPath) {   
  7.        String txt = folderPath;   
  8.        try {   
  9.            java.io.File myFilePath = new java.io.File(txt);   
  10.            txt = folderPath;   
  11.            if (!myFilePath.exists()) {   
  12.                myFilePath.mkdir();   
  13.            }   
  14.        } catch (Exception e) {   
  15.            message = "创建目录操作出错";   
  16.        }   
  17.        return txt;   
  18.    }  

 

Java代码 复制代码
  1. /**  
  2.      * 多级目录创建  
  3.      * @param folderPath 准备要在本级目录下创建新目录的目录路径 例如 c:myf  
  4.      * @param paths 无限级目录参数,各级目录以单数线区分 例如 a|b|c  
  5.      * @return 返回创建文件后的路径 例如 c:myfa c  
  6.      */  
  7.     public String createFolders(String folderPath, String paths) {   
  8.         String txts = folderPath;   
  9.         try {   
  10.             String txt;   
  11.             txts = folderPath;   
  12.             StringTokenizer st = new StringTokenizer(paths, "|");   
  13.             for (int i = 0; st.hasMoreTokens(); i++) {   
  14.                 txt = st.nextToken().trim();   
  15.                 if (txts.lastIndexOf("/") != -1) {   
  16.                     txts = createFolder(txts + txt);   
  17.                 } else {   
  18.                     txts = createFolder(txts + txt + "/");   
  19.                 }   
  20.             }   
  21.         } catch (Exception e) {   
  22.             message = "创建目录操作出错!";   
  23.         }   
  24.         return txts;   
  25.     }  

 

Java代码 复制代码
  1. /**  
  2.      * 新建文件  
  3.      * @param filePathAndName 文本文件完整绝对路径及文件名  
  4.      * @param fileContent 文本文件内容  
  5.      * @return  
  6.      */  
  7.     public void createFile(String filePathAndName, String fileContent) {   
  8.   
  9.         try {   
  10.             String filePath = filePathAndName;   
  11.             filePath = filePath.toString();   
  12.             File myFilePath = new File(filePath);   
  13.             if (!myFilePath.exists()) {   
  14.                 myFilePath.createNewFile();   
  15.             }   
  16.             FileWriter resultFile = new FileWriter(myFilePath);   
  17.             PrintWriter myFile = new PrintWriter(resultFile);   
  18.             String strContent = fileContent;   
  19.             myFile.println(strContent);   
  20.             myFile.close();   
  21.             resultFile.close();   
  22.         } catch (Exception e) {   
  23.             message = "创建文件操作出错";   
  24.         }   
  25.     }  
Java代码 复制代码
  1. /**  
  2.      * 有编码方式的文件创建  
  3.      * @param filePathAndName 文本文件完整绝对路径及文件名  
  4.      * @param fileContent 文本文件内容  
  5.      * @param encoding 编码方式 例如 GBK 或者 UTF-8  
  6.      * @return  
  7.      */  
  8.     public void createFile(String filePathAndName, String fileContent,   
  9.         String encoding) {   
  10.   
  11.         try {   
  12.             String filePath = filePathAndName;   
  13.             filePath = filePath.toString();   
  14.             File myFilePath = new File(filePath);   
  15.             if (!myFilePath.exists()) {   
  16.                 myFilePath.createNewFile();   
  17.             }   
  18.             PrintWriter myFile = new PrintWriter(myFilePath, encoding);   
  19.             String strContent = fileContent;   
  20.             myFile.println(strContent);   
  21.             myFile.close();   
  22.         } catch (Exception e) {   
  23.             message = "创建文件操作出错";   
  24.         }   
  25.     }  

 

Java代码 复制代码
  1. /**  
  2.     * 删除文件  
  3.     * @param filePathAndName 文本文件完整绝对路径及文件名  
  4.     * @return Boolean 成功删除返回true遭遇异常返回false  
  5.     */  
  6.    public boolean delFile(String filePathAndName) {   
  7.        boolean bea = false;   
  8.        try {   
  9.            String filePath = filePathAndName;   
  10.            File myDelFile = new File(filePath);   
  11.            if (myDelFile.exists()) {   
  12.                myDelFile.delete();   
  13.                bea = true;   
  14.            } else {   
  15.                bea = false;   
  16.                message = (filePathAndName + " 删除文件操作出错");   
  17.            }   
  18.        } catch (Exception e) {   
  19.            message = e.toString();   
  20.        }   
  21.        return bea;   
  22.    }  

 

Java代码 复制代码
  1. /**  
  2.      * 删除文件夹  
  3.      * @param folderPath 文件夹完整绝对路径  
  4.      * @return  
  5.      */  
  6.     public void delFolder(String folderPath) {   
  7.         try {   
  8.             delAllFile(folderPath); // 删除完里面所有内容   
  9.             String filePath = folderPath;   
  10.             filePath = filePath.toString();   
  11.             java.io.File myFilePath = new java.io.File(filePath);   
  12.             myFilePath.delete(); // 删除空文件夹   
  13.         } catch (Exception e) {   
  14.             message = ("删除文件夹操作出错");   
  15.         }   
  16.     }   
  17.   
  18.   
  19.     /**  
  20.      * 删除指定文件夹下所有文件  
  21.      * @param path 文件夹完整绝对路径  
  22.      * @return  
  23.      * @return  
  24.      */  
  25.     public boolean delAllFile(String path) {   
  26.         boolean bea = false;   
  27.         File file = new File(path);   
  28.         if (!file.exists()) {   
  29.             return bea;   
  30.         }   
  31.         if (!file.isDirectory()) {   
  32.             return bea;   
  33.         }   
  34.         String[] tempList = file.list();   
  35.         File temp = null;   
  36.         for (int i = 0; i < tempList.length; i++) {   
  37.             if (path.endsWith(File.separator)) {   
  38.                 temp = new File(path + tempList[i]);   
  39.             } else {   
  40.                 temp = new File(path + File.separator + tempList[i]);   
  41.             }   
  42.             if (temp.isFile()) {   
  43.                 temp.delete();   
  44.             }   
  45.             if (temp.isDirectory()) {   
  46.                 delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件   
  47.                 delFolder(path + "/" + tempList[i]);// 再删除空文件夹   
  48.                 bea = true;   
  49.             }   
  50.         }   
  51.         return bea;   
  52.     }  

 

Java代码 复制代码
  1. /**  
  2.      * 复制单个文件  
  3.      * @param oldPathFile 准备复制的文件源  
  4.      * @param newPathFile 拷贝到新绝对路径带文件名  
  5.      * @return  
  6.      */  
  7.     public void copyFile(String oldPathFile, String newPathFile) {   
  8.         try {   
  9.             int bytesum = 0;   
  10.             int byteread = 0;   
  11.             File oldfile = new File(oldPathFile);   
  12.             if (oldfile.exists()) { // 文件存在时   
  13.                 InputStream inStream = new FileInputStream(oldPathFile); // 读入原文件   
  14.                 FileOutputStream fs = new FileOutputStream(newPathFile);   
  15.                 byte[] buffer = new byte[1444];   
  16.                 while ((byteread = inStream.read(buffer)) != -1) {   
  17.                     bytesum += byteread; // 字节数 文件大小   
  18.                     System.out.println(bytesum);   
  19.                     fs.write(buffer, 0, byteread);   
  20.                 }   
  21.                 inStream.close();   
  22.             }   
  23.         } catch (Exception e) {   
  24.             message = ("复制单个文件操作出错");   
  25.         }   
  26.     }  

 

Java代码 复制代码
  1. /**  
  2.      * 复制整个文件夹的内容  
  3.      * @param oldPath 准备拷贝的目录  
  4.      * @param newPath 指定绝对路径的新目录  
  5.      * @return  
  6.      */  
  7.     public void copyFolder(String oldPath, String newPath) {   
  8.         try {   
  9.             new File(newPath).mkdirs(); // 如果文件夹不存在 则建立新文件夹   
  10.             File a = new File(oldPath);   
  11.             String[] file = a.list();   
  12.             File temp = null;   
  13.             for (int i = 0; i < file.length; i++) {   
  14.                 if (oldPath.endsWith(File.separator)) {   
  15.                     temp = new File(oldPath + file[i]);   
  16.                 } else {   
  17.                     temp = new File(oldPath + File.separator + file[i]);   
  18.                 }   
  19.                 if (temp.isFile()) {   
  20.                     FileInputStream input = new FileInputStream(temp);   
  21.                     FileOutputStream output = new FileOutputStream(newPath   
  22.                         + "/" + (temp.getName()).toString());   
  23.                     byte[] b = new byte[1024 * 5];   
  24.                     int len;   
  25.                     while ((len = input.read(b)) != -1) {   
  26.                         output.write(b, 0, len);   
  27.                     }   
  28.                     output.flush();   
  29.                     output.close();   
  30.                     input.close();   
  31.                 }   
  32.                 if (temp.isDirectory()) {// 如果是子文件夹   
  33.                     copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);   
  34.                 }   
  35.             }   
  36.         } catch (Exception e) {   
  37.             message = "复制整个文件夹内容操作出错";   
  38.         }   
  39.     }  

 

Java代码 复制代码
  1. /**  
  2.   * 移动文件  
  3.   * @param oldPath  
  4.   * @param newPath  
  5.   * @return  
  6.   */  
  7.  public void moveFile(String oldPath, String newPath) {   
  8.      copyFile(oldPath, newPath);   
  9.      delFile(oldPath);   
  10.  }  

 

Java代码 复制代码
  1. /**  
  2.     * 移动目录  
  3.     * @param oldPath  
  4.     * @param newPath  
  5.     * @return  
  6.     */  
  7.    public void moveFolder(String oldPath, String newPath) {   
  8.        copyFolder(oldPath, newPath);   
  9.        delFolder(oldPath);   
  10.    }  
原创粉丝点击