File的相关方法代码实例

1:Java多种读取文件的方式

  1. import java.io.BufferedReader;  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileReader;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.io.RandomAccessFile;  
  10. import java.io.Reader;  
  11.   
  12. public class MultiJavaReadFiles {  
  13.     /** 
  14.      * 以字节为单位读取文件,常用于读二进制文件,例如图片、声音、影像等文件 
  15.      * @param fileName 
  16.      */  
  17.     private static void readFileByBytes(String fileName) {  
  18.         File file = new File(fileName);  
  19.         InputStream in = null;  
  20.           
  21.         try {  
  22.             System.out.println("以字节为单位读取文件内容,一次读一个字节:");  
  23.             in = new FileInputStream(file);  
  24.             int tempbyte;  
  25.             while((tempbyte = in.read()) != -1) {  
  26.                 System.out.println(tempbyte);  
  27.             }  
  28.             in.close();  
  29.         } catch (FileNotFoundException e) {  
  30.             e.printStackTrace();  
  31.         } catch (IOException e) {  
  32.             e.printStackTrace();  
  33.         }  
  34.           
  35.         try {  
  36.             System.out.println("以字节为单位读取文件内容,一次读多个字节:");  
  37.             byte[] tempbytes = new byte[100];  
  38.             int byteread = 0;  
  39.             in = new FileInputStream(file);  
  40.             //读取多个字节到数组中,byteread为一次读入的字节数  
  41.             while((byteread = in.read(tempbytes)) != -1) {  
  42.                 System.out.write(tempbytes, 0, byteread);  
  43.             }  
  44.         } catch (FileNotFoundException e) {  
  45.             e.printStackTrace();  
  46.         } catch (IOException e) {  
  47.             e.printStackTrace();  
  48.         } finally {  
  49.             if(in != null) {  
  50.                 try {  
  51.                     in.close();  
  52.                 } catch (IOException e) {  
  53.                     e.printStackTrace();  
  54.                 }  
  55.             }  
  56.         }  
  57.     }  
  58.       
  59.     /** 
  60.      * 按字符读文件,常用于读文本,数字等类型文件 
  61.      * @param fileName 
  62.      */  
  63.     private static void readFileByChars(String fileName) {  
  64.         File file = new File(fileName);  
  65.         Reader reader = null;  
  66.         try {  
  67.             System.out.println("以字符为单位读取文件内容,一次读取一个字符:");  
  68.             //一次读一个字符  
  69.             reader = new InputStreamReader(new FileInputStream(file));  
  70.             int tempchar;  
  71.             while((tempchar = reader.read()) != -1) {  
  72.                 //对于windows下,rn这两个字符在一起时,表示一个换行。    
  73.                 //但如果这两个字符分开显示时,会换两次行。    
  74.                 //因此,屏蔽掉r,或者屏蔽n。否则,将会多出很多空行。  
  75.                 if((char)tempchar != 'r') {  
  76.                     System.out.println((char)tempchar);  
  77.                 }  
  78.                 reader.close();  
  79.             }  
  80.         } catch (FileNotFoundException e) {  
  81.             e.printStackTrace();  
  82.         } catch (IOException e) {  
  83.             e.printStackTrace();  
  84.         }  
  85.           
  86.         try {  
  87.             System.out.println("以字符为单位读取文件内容,一次读取多个字符:");  
  88.             char[] tempchars = new char[30];  
  89.             int charread = 0;  
  90.             reader = new InputStreamReader(new FileInputStream(file));  
  91.             //读入多个字符到字符数组中,charread为一次读取字符数   
  92.             //read(char[] tempchars)方法把字符读入数组,并且返回读取的字符数,如果已到达流的末尾,则返回 -1   
  93.             while((charread = reader.read(tempchars)) != -1) {  
  94.                 //屏蔽掉r不显示  
  95.                 if((charread == tempchars.length) && (tempchars[tempchars.length - 1]) != -1) {  
  96.                     System.out.println(tempchars);  
  97.                 } else {  
  98.                     for(int i=0; i<charread; i++) {  
  99.                         if(tempchars[i] == 'r') {  
  100.                             continue;  
  101.                         } else {  
  102.                             System.out.println(tempchars[i]);  
  103.                         }  
  104.                     }  
  105.                 }  
  106.             }  
  107.         } catch (FileNotFoundException e) {  
  108.             e.printStackTrace();  
  109.         } catch (IOException e) {  
  110.             e.printStackTrace();  
  111.         } finally {  
  112.             if(reader != null) {  
  113.                 try {  
  114.                     reader.close();  
  115.                 } catch (IOException e) {  
  116.                     e.printStackTrace();  
  117.                 }  
  118.             }  
  119.         }  
  120.           
  121.   
  122.     }  
  123.       
  124.     /**  
  125.      * 以行为单位读取文件,常用于读面向行的格式化文件  
  126.      * @param fileName 文件名  
  127.      */    
  128.     public static void readFileByLines(String fileName) {  
  129.         File file = new File(fileName);  
  130.         BufferedReader reader = null;  
  131.         try {  
  132.             System.out.println("以行为单位读取文件内容,一次读一整行:");  
  133.             reader = new BufferedReader(new FileReader(file));  
  134.             String tempString = null;  
  135.             int line = 1;  
  136.             // 一次读入一行,直到读入null为文件结束  
  137.             while ((tempString = reader.readLine()) != null) {  
  138.                 // 显示行号  
  139.                 System.out.println("line " + line + ": " + tempString);  
  140.                 line++;  
  141.             }  
  142.             reader.close();  
  143.         } catch (IOException e) {  
  144.             e.printStackTrace();  
  145.         } finally {  
  146.             if (reader != null) {  
  147.                 try {  
  148.                     reader.close();  
  149.                 } catch (IOException e1) {  
  150.                 }  
  151.             }  
  152.         }  
  153.     }  
  154.       
  155.     /**  
  156.     * 随机读取文件内容  
  157.     * @param fileName 文件名  
  158.     */    
  159.     public static void readFileByRandomAccess(String fileName) {  
  160.         RandomAccessFile randomFile = null;  
  161.         try {  
  162.             System.out.println("随机读取一段文件内容:");  
  163.             // 打开一个随机访问文件流,按只读方式  
  164.             randomFile = new RandomAccessFile(fileName, "r");  
  165.             // 文件长度,字节数  
  166.             long fileLength = randomFile.length();  
  167.             // 读文件的起始位置  
  168.             int beginIndex = (fileLength > 4) ? 4 : 0;  
  169.             // 将读文件的开始位置移到beginIndex位置。  
  170.             randomFile.seek(beginIndex);  
  171.             byte[] bytes = new byte[10];  
  172.             int byteread = 0;  
  173.             // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。  
  174.             // 将一次读取的字节数赋给byteread  
  175.             while ((byteread = randomFile.read(bytes)) != -1) {  
  176.                 System.out.write(bytes, 0, byteread);  
  177.             }  
  178.         } catch (IOException e) {  
  179.             e.printStackTrace();  
  180.         } finally {  
  181.             if (randomFile != null) {  
  182.                 try {  
  183.                     randomFile.close();  
  184.                 } catch (IOException e1) {  
  185.                 }  
  186.             }  
  187.         }  
  188.     }  
  189.   
  190.     /**  
  191.     * 显示输入流中还剩的字节数  
  192.     * @param in  
  193.     */    
  194.     private static void showAvailableBytes(InputStream in) {  
  195.         try {  
  196.             System.out.println("当前字节输入流中的字节数为:" + in.available());  
  197.         } catch (IOException e) {  
  198.             e.printStackTrace();  
  199.         }  
  200.     }  
  201.       
  202.     public static void main(String[] args) {    
  203.         String fileName = "C:/temp/newTemp.txt";    
  204.         MultiJavaReadFiles.readFileByBytes(fileName);    
  205.         MultiJavaReadFiles.readFileByChars(fileName);    
  206.         MultiJavaReadFiles.readFileByLines(fileName);    
  207.         MultiJavaReadFiles.readFileByRandomAccess(fileName);    
  208.     }     

2 Java对文件的操作/列出目录以及下面的所有文件

  1. import java.io.*;  
  2.   
  3. public class FileOperate {  
  4.     public FileOperate() {  
  5.     }  
  6.   
  7.     /** 
  8.      * 新建目录 
  9.      *  
  10.      * @param folderPath 
  11.      *            String 如 c:/fqf 
  12.      * @return boolean 
  13.      */  
  14.     public void newFolder(String folderPath) {  
  15.         try {  
  16.             String filePath = folderPath;  
  17.             filePath = filePath.toString();  
  18.             java.io.File myFilePath = new java.io.File(filePath);  
  19.             if (!myFilePath.exists()) {  
  20.                 myFilePath.mkdir();  
  21.             }  
  22.         } catch (Exception e) {  
  23.             System.out.println("新建目录操作出错 ");  
  24.             e.printStackTrace();  
  25.         }  
  26.     }  
  27.   
  28.     /** 
  29.      * 新建文件 
  30.      *  
  31.      * @param filePathAndName 
  32.      *            String 文件路径及名称 如c:/fqf.txt 
  33.      * @param fileContent 
  34.      *            String 文件内容 
  35.      * @return boolean 
  36.      */  
  37.     public void newFile(String filePathAndName, String fileContent) {  
  38.   
  39.         try {  
  40.             String filePath = filePathAndName;  
  41.             filePath = filePath.toString();  
  42.             File myFilePath = new File(filePath);  
  43.             if (!myFilePath.exists()) {  
  44.                 myFilePath.createNewFile();  
  45.             }  
  46.             FileWriter resultFile = new FileWriter(myFilePath);  
  47.             PrintWriter myFile = new PrintWriter(resultFile);  
  48.             String strContent = fileContent;  
  49.             myFile.println(strContent);  
  50.             resultFile.close();  
  51.   
  52.         } catch (Exception e) {  
  53.             System.out.println("新建目录操作出错 ");  
  54.             e.printStackTrace();  
  55.   
  56.         }  
  57.   
  58.     }  
  59.   
  60.     /** 
  61.      * 删除文件 
  62.      *  
  63.      * @param filePathAndName 
  64.      *            String 文件路径及名称 如c:/fqf.txt 
  65.      * @param fileContent 
  66.      *            String 
  67.      * @return boolean 
  68.      */  
  69.     public void delFile(String filePathAndName) {  
  70.         try {  
  71.             String filePath = filePathAndName;  
  72.             filePath = filePath.toString();  
  73.             java.io.File myDelFile = new java.io.File(filePath);  
  74.             myDelFile.delete();  
  75.   
  76.         } catch (Exception e) {  
  77.             System.out.println("删除文件操作出错 ");  
  78.             e.printStackTrace();  
  79.   
  80.         }  
  81.   
  82.     }  
  83.   
  84.     /** 
  85.      * 删除文件夹 
  86.      *  
  87.      * @param filePathAndName 
  88.      *            String 文件夹路径及名称 如c:/fqf 
  89.      * @param fileContent 
  90.      *            String 
  91.      * @return boolean 
  92.      */  
  93.     public void delFolder(String folderPath) {  
  94.         try {  
  95.             delAllFile(folderPath); // 删除完里面所有内容  
  96.             String filePath = folderPath;  
  97.             filePath = filePath.toString();  
  98.             java.io.File myFilePath = new java.io.File(filePath);  
  99.             myFilePath.delete(); // 删除空文件夹  
  100.   
  101.         } catch (Exception e) {  
  102.             System.out.println("删除文件夹操作出错 ");  
  103.             e.printStackTrace();  
  104.   
  105.         }  
  106.   
  107.     }  
  108.   
  109.     /** 
  110.      * 删除文件夹里面的所有文件 
  111.      *  
  112.      * @param path 
  113.      *            String 文件夹路径 如 c:/fqf 
  114.      */  
  115.     public void delAllFile(String path) {  
  116.         File file = new File(path);  
  117.         if (!file.exists()) {  
  118.             return;  
  119.         }  
  120.         if (!file.isDirectory()) {  
  121.             return;  
  122.         }  
  123.         String[] tempList = file.list();  
  124.         File temp = null;  
  125.         for (int i = 0; i < tempList.length; i++) {  
  126.             if (path.endsWith(File.separator)) {  
  127.                 temp = new File(path + tempList[i]);  
  128.             } else {  
  129.                 temp = new File(path + File.separator + tempList[i]);  
  130.             }  
  131.             if (temp.isFile()) {  
  132.                 temp.delete();  
  133.             }  
  134.             if (temp.isDirectory()) {  
  135.                 delAllFile(path + "/ " + tempList[i]);// 先删除文件夹里面的文件  
  136.                 delFolder(path + "/ " + tempList[i]);// 再删除空文件夹  
  137.             }  
  138.         }  
  139.     }  
  140.   
  141.     /** 
  142.      * 复制单个文件 
  143.      *  
  144.      * @param oldPath 
  145.      *            String 原文件路径 如:c:/fqf.txt 
  146.      * @param newPath 
  147.      *            String 复制后路径 如:f:/fqf.txt 
  148.      * @return boolean 
  149.      */  
  150.     public void copyFile(String oldPath, String newPath) {  
  151.         try {  
  152.             int bytesum = 0;  
  153.             int byteread = 0;  
  154.             File oldfile = new File(oldPath);  
  155.             if (oldfile.exists()) { // 文件存在时  
  156.                 InputStream inStream = new FileInputStream(oldPath); // 读入原文件  
  157.                 FileOutputStream fs = new FileOutputStream(newPath);  
  158.                 byte[] buffer = new byte[1444];  
  159.                 int length;  
  160.                 while ((byteread = inStream.read(buffer)) != -1) {  
  161.                     bytesum += byteread; // 字节数 文件大小  
  162.                     System.out.println(bytesum);  
  163.                     fs.write(buffer, 0, byteread);  
  164.                 }  
  165.                 inStream.close();  
  166.             }  
  167.         } catch (Exception e) {  
  168.             System.out.println("复制单个文件操作出错 ");  
  169.             e.printStackTrace();  
  170.   
  171.         }  
  172.   
  173.     }  
  174.   
  175.     /** 
  176.      * 复制整个文件夹内容 
  177.      *  
  178.      * @param oldPath 
  179.      *            String 原文件路径 如:c:/fqf 
  180.      * @param newPath 
  181.      *            String 复制后路径 如:f:/fqf/ff 
  182.      * @return boolean 
  183.      */  
  184.     public void copyFolder(String oldPath, String newPath) {  
  185.   
  186.         try {  
  187.             (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹  
  188.             File a = new File(oldPath);  
  189.             String[] file = a.list();  
  190.             File temp = null;  
  191.             for (int i = 0; i < file.length; i++) {  
  192.                 if (oldPath.endsWith(File.separator)) {  
  193.                     temp = new File(oldPath + file[i]);  
  194.                 } else {  
  195.                     temp = new File(oldPath + File.separator + file[i]);  
  196.                 }  
  197.   
  198.                 if (temp.isFile()) {  
  199.                     FileInputStream input = new FileInputStream(temp);  
  200.                     FileOutputStream output = new FileOutputStream(newPath  
  201.                             + "/ " + (temp.getName()).toString());  
  202.                     byte[] b = new byte[1024 * 5];  
  203.                     int len;  
  204.                     while ((len = input.read(b)) != -1) {  
  205.                         output.write(b, 0, len);  
  206.                     }  
  207.                     output.flush();  
  208.                     output.close();  
  209.                     input.close();  
  210.                 }  
  211.                 if (temp.isDirectory()) {// 如果是子文件夹  
  212.                     copyFolder(oldPath + "/ " + file[i], newPath + "/ "  
  213.                             + file[i]);  
  214.                 }  
  215.             }  
  216.         } catch (Exception e) {  
  217.             System.out.println("复制整个文件夹内容操作出错 ");  
  218.             e.printStackTrace();  
  219.   
  220.         }  
  221.   
  222.     }  
  223.   
  224.     /** 
  225.      * 移动文件到指定目录 
  226.      *  
  227.      * @param oldPath 
  228.      *            String 如:c:/fqf.txt 
  229.      * @param newPath 
  230.      *            String 如:d:/fqf.txt 
  231.      */  
  232.     public void moveFile(String oldPath, String newPath) {  
  233.         copyFile(oldPath, newPath);  
  234.         delFile(oldPath);  
  235.   
  236.     }  
  237.   
  238.     /** 
  239.      * 移动文件到指定目录 
  240.      *  
  241.      * @param oldPath 
  242.      *            String 如:c:/fqf.txt 
  243.      * @param newPath 
  244.      *            String 如:d:/fqf.txt 
  245.      */  
  246.     public void moveFolder(String oldPath, String newPath) {  
  247.         copyFolder(oldPath, newPath);  
  248.         delFolder(oldPath);  
  249.   
  250.     }  
  251. }  

法1:


  1. import java.io.File;  
  2.   
  3. public class Filedic {  
  4.     public static void main(String []args) {  
  5.         //编写一个程序把对应盘符下面的所有文件或者文件夹有层次(树状)结构列出来  
  6.         String pathname="D:\\";  
  7.         Filedic chap =new Filedic();  
  8.         chap.forListDirFile(pathname);  
  9.     }  
  10.       
  11.     /** 
  12.      * 使用递归算法,进行文件或目录的显示 
  13.      * @param pathname 
  14.      */  
  15.     public void forListDirFile(String pathname){  
  16.         File file = new File(pathname);  
  17.         if(file.exists()) {   
  18.             if(file.isFile()) {  
  19.                 System.out.println(file.getName());  
  20.                   
  21.             } else if(file.isDirectory()){    
  22.                 File[] list_files=file.listFiles();  
  23.                 if(null!=list_files){  
  24.                     for(int i=0;i<list_files.length;i++) {  
  25.                         System.out.println(list_files[i]);  
  26.                         this.forListDirFile(list_files[i].toString());   
  27.                     }   
  28.                 } else {  
  29.                     System.out.println("此路径为空");  
  30.                 }  
  31.                   
  32.             } else {  
  33.                 System.out.println(file.getName());  
  34.             }   
  35.         }  
  36.            
  37.     }  
  38.       
  39.       
  40. }  


法2:


  1. import java.io.*;  
  2.   
  3. public class FileDics {  
  4.   
  5.     public static void main(String[] args) {  
  6.         File f = new File("D:/");  
  7.         System.out.println(f.getPath() + f.getName());  
  8.         tree(f);  
  9.     }  
  10.   
  11.     private static void tree(File f) {  
  12.   
  13.         File[] childs = f.listFiles();// 列出目录下所有的文件  
  14.         for (int i = 0; i < childs.length-1; i++) {  
  15.             System.out.println(childs[i].getPath() + childs[i].getName());  
  16.             if (childs[i].isDirectory()) {  
  17.                 tree(childs[i]);// 如果是个目录,就继续递归列出其下面的文件.  
  18.             }  
  19.         }  
  20.     }  
  21. }  



原文地址:https://www.cnblogs.com/allenzhaox/p/3201823.html