• Java对文件的操作(增,删,改)


      1 //文件的各种操作类
      2 import java.io.*;
      3 
      4 class FileOperate
      5 {
      6     
      7     /**
      8     * 新建目录
      9     */
     10     public void newFolder(String folderPath)
     11     {
     12         try
     13         {
     14             String filePath = folderPath;
     15             filePath = filePath.toString();
     16             File myFilePath = new File(filePath);
     17             if(!myFilePath.exists())
     18             {
     19                 myFilePath.mkdir();
     20             }
     21             System.out.println("新建目录操作 成功执行");
     22         }
     23         catch(Exception e)
     24         {
     25             System.out.println("新建目录操作出错");
     26             e.printStackTrace();
     27         }
     28     }
     29     
     30     /**
     31     * 新建文件
     32     */
     33     public void newFile(String filePathAndName, String fileContent)
     34     {
     35         try
     36         {
     37             String filePath = filePathAndName;
     38             filePath = filePath.toString();
     39             File myFilePath = new File(filePath);
     40             if (!myFilePath.exists())
     41             {
     42                 myFilePath.createNewFile();
     43             }
     44             FileWriter resultFile = new FileWriter(myFilePath);
     45             PrintWriter myFile = new PrintWriter(resultFile);
     46             String strContent = fileContent;
     47             myFile.println(strContent);
     48             resultFile.close();
     49             System.out.println("新建文件操作 成功执行");
     50         }
     51         catch (Exception e)
     52         {
     53             System.out.println("新建目录操作出错");
     54             e.printStackTrace();
     55         }
     56     }
     57     
     58     /**
     59     * 删除文件
     60     */
     61     public void delFile(String filePathAndName)
     62     {
     63         try
     64         {
     65             String filePath = filePathAndName;
     66             filePath = filePath.toString();
     67             File myDelFile = new File(filePath);
     68             myDelFile.delete();
     69             System.out.println("删除文件操作 成功执行");
     70         }
     71         catch (Exception e)
     72         {
     73             System.out.println("删除文件操作出错");
     74             e.printStackTrace();
     75         }
     76     }
     77     
     78     /**
     79     * 删除文件夹
     80     */
     81     public void delFolder(String folderPath)
     82     {
     83         try
     84         {
     85             delAllFile(folderPath); //删除完里面所有内容
     86             String filePath = folderPath;
     87             filePath = filePath.toString();
     88             File myFilePath = new File(filePath);
     89             if(myFilePath.delete())
     90             { //删除空文件夹
     91                 System.out.println("删除文件夹" + folderPath + "操作 成功执行");
     92             } else 
     93             {
     94                 System.out.println("删除文件夹" + folderPath + "操作 执行失败");
     95             }
     96         }
     97         catch (Exception e)
     98         {
     99             System.out.println("删除文件夹操作出错");
    100             e.printStackTrace();
    101         }
    102     }
    103     
    104     /**
    105     * 删除文件夹里面的所有文件
    106     * @param path String 文件夹路径 如 c:/fqf
    107     */
    108     public void delAllFile(String path)
    109     {
    110         File file = new File(path);
    111         if(!file.exists())
    112         {
    113             return;
    114         }
    115         if(!file.isDirectory())
    116         {
    117             return;
    118         }
    119         String[] tempList = file.list();
    120         File temp = null;
    121         for (int i = 0; i < tempList.length; i++)
    122         {
    123             if(path.endsWith(File.separator))
    124             {
    125                 temp = new File(path + tempList[i]);
    126             }
    127             else
    128             {
    129                 temp = new File(path + File.separator + tempList[i]);
    130             }
    131             if (temp.isFile())
    132             {
    133                 temp.delete();
    134             }
    135             if (temp.isDirectory())
    136             {
    137                 //delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
    138                 delFolder(path+ File.separatorChar + tempList[i]);//再删除空文件夹
    139             }
    140         }
    141         System.out.println("删除文件操作 成功执行");
    142     }
    143     
    144     /**
    145     * 复制单个文件
    146     * @param oldPath String 原文件路径 如:c:/fqf.txt
    147     * @param newPath String 复制后路径 如:f:/fqf.txt
    148     */
    149     public void copyFile(String oldPath, String newPath)
    150     {
    151         try
    152         {
    153             int bytesum = 0;
    154             int byteread = 0;
    155             File oldfile = new File(oldPath);
    156             if (oldfile.exists())
    157             {
    158                 //文件存在时
    159                 InputStream inStream = new FileInputStream(oldPath); //读入原文件
    160                 FileOutputStream fs = new FileOutputStream(newPath);
    161                 byte[] buffer = new byte[1444];
    162                 while ( (byteread = inStream.read(buffer)) != -1)
    163                 {
    164                     bytesum += byteread; //字节数 文件大小
    165                     System.out.println(bytesum);
    166                     fs.write(buffer, 0, byteread);
    167                 }
    168                 inStream.close();
    169             }
    170             System.out.println("删除文件夹操作 成功执行");
    171         }
    172         catch (Exception e)
    173         {
    174             System.out.println("复制单个文件操作出错");
    175             e.printStackTrace();
    176         }
    177     }
    178     
    179     /**
    180     * 复制整个文件夹内容
    181     * @param oldPath String 原文件路径 如:c:/fqf
    182     * @param newPath String 复制后路径 如:f:/fqf/ff
    183     */
    184     public void copyFolder(String oldPath, String newPath)
    185     {
    186         try
    187         {
    188             (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
    189             File a=new File(oldPath);
    190             String[] file=a.list();
    191             File temp=null;
    192             for (int i = 0; i < file.length; i++)
    193             {
    194                 if(oldPath.endsWith(File.separator))
    195                 {
    196                     temp=new File(oldPath+file[i]);
    197                 }
    198                 else
    199                 {
    200                     temp=new File(oldPath+File.separator+file[i]);
    201                 }
    202                 if(temp.isFile())
    203                 {
    204                     FileInputStream input = new FileInputStream(temp);
    205                     FileOutputStream output = new FileOutputStream(newPath + "/" +
    206                     (temp.getName()).toString());
    207                     byte[] b = new byte[1024 * 5];
    208                     int len;
    209                     while ( (len = input.read(b)) != -1)
    210                     {
    211                         output.write(b, 0, len);
    212                     }
    213                     output.flush();
    214                     output.close();
    215                     input.close();
    216                 }
    217                 if(temp.isDirectory())
    218                 {
    219                     //如果是子文件夹
    220                     copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
    221                 }
    222             }
    223             System.out.println("复制文件夹操作 成功执行");
    224         }
    225         catch (Exception e)
    226         {
    227             System.out.println("复制整个文件夹内容操作出错");
    228             e.printStackTrace();
    229         }
    230     }
    231     
    232     /**
    233     * 移动文件到指定目录
    234     * @param oldPath String 如:c:/fqf.txt
    235     * @param newPath String 如:d:/fqf.txt
    236     */
    237     public void moveFile(String oldPath, String newPath)
    238     {
    239         copyFile(oldPath, newPath);
    240         delFile(oldPath);
    241     }
    242     
    243     /**
    244     * 移动文件到指定目录
    245     * @param oldPath String 如:c:/fqf.txt
    246     * @param newPath String 如:d:/fqf.txt
    247     */
    248     public void moveFolder(String oldPath, String newPath)
    249     {
    250         copyFolder(oldPath, newPath);
    251         delFolder(oldPath);
    252     }
    253     
    254     /**
    255     * A方法追加文件:使用RandomAccessFile
    256     * @param fileName 文件名
    257     * @param content 追加的内容
    258     */
    259     public static void appendMethodA(String fileName, String content)
    260     {
    261         try 
    262         {
    263             // 打开一个随机访问文件流,按读写方式
    264             RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
    265             // 文件长度,字节数
    266             long fileLength = randomFile.length();
    267             //将写文件指针移到文件尾。
    268             randomFile.seek(fileLength);
    269             randomFile.writeBytes(content);
    270             randomFile.close();
    271         } catch (IOException e)
    272         {
    273             e.printStackTrace();
    274         }
    275     }
    276     
    277     /**
    278     * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
    279     * @param fileName 文件的名
    280     */
    281     public static void readFileByBytes(String fileName)
    282     {
    283         File file = new File(fileName);
    284         InputStream in = null;
    285         try
    286         {
    287             System.out.println("以字节为单位读取文件内容,一次读一个字节:");
    288             // 一次读一个字节
    289             in = new FileInputStream(file);
    290             int tempbyte;
    291             while((tempbyte=in.read()) != -1)
    292             {
    293                 System.out.write(tempbyte);
    294             }
    295             in.close();
    296         } catch (IOException e)
    297         {
    298             e.printStackTrace();
    299             return;
    300         }
    301         try 
    302         {
    303             System.out.println("以字节为单位读取文件内容,一次读多个字节:");
    304             //一次读多个字节
    305             byte[] tempbytes = new byte[100];
    306             int byteread = 0;
    307             in = new FileInputStream(fileName);
    308             //ReadFromFile.showAvailableBytes(in);
    309             //读入多个字节到字节数组中,byteread为一次读入的字节数
    310             while ((byteread = in.read(tempbytes)) != -1)
    311             {
    312                 System.out.write(tempbytes, 0, byteread);
    313             }
    314         } catch (Exception e1) 
    315         {
    316             e1.printStackTrace();
    317         } finally
    318         {
    319             if(in != null)
    320             {
    321                 try
    322                 {
    323                     in.close();
    324                 } catch (IOException e1)
    325                 {
    326                 }
    327             }
    328         }
    329     }
    330     
    331     /**
    332     * 以字符为单位读取文件,常用于读文本,数字等类型的文件
    333     * @param fileName 文件名
    334     */
    335     public static void readFileByChars(String fileName)
    336     {
    337         File file = new File(fileName);
    338         Reader reader = null;
    339         try
    340         {
    341             System.out.println("以字符为单位读取文件内容,一次读一个字节:");
    342             // 一次读一个字符
    343             reader = new InputStreamReader(new FileInputStream(file));
    344             int tempchar;
    345             while ((tempchar = reader.read()) != -1)
    346             {
    347                 //对于windows下,这两个字符在一起时,表示一个换行。
    348                 //但如果这两个字符分开显示时,会换两次行。
    349                 //因此,屏蔽掉,或者屏蔽。否则,将会多出很多空行。
    350                 if (((char)tempchar) != ' ')
    351                 {
    352                     System.out.print((char)tempchar);
    353                 }
    354             }
    355             reader.close();
    356         } catch (Exception e) 
    357         {
    358             e.printStackTrace();
    359         }
    360         try 
    361         {
    362             System.out.println("以字符为单位读取文件内容,一次读多个字节:");
    363             //一次读多个字符
    364             char[] tempchars = new char[30];
    365             int charread = 0;
    366             reader = new InputStreamReader(new FileInputStream(fileName));
    367             //读入多个字符到字符数组中,charread为一次读取字符数
    368             while ((charread = reader.read(tempchars)) != -1)
    369             {
    370                 //同样屏蔽掉不显示
    371                 if ((charread == tempchars.length) && (tempchars[tempchars.length-1] != ' '))
    372                 {
    373                     System.out.print(tempchars);
    374                 }else
    375                 {
    376                     for (int i=0; i<charread; i++)
    377                     {
    378                         if(tempchars[i] == ' ')
    379                         {
    380                             continue;
    381                         }else
    382                         {
    383                             System.out.print(tempchars[i]);
    384                         }
    385                     }
    386                 }
    387             }
    388         } catch (Exception e1) 
    389         {
    390             e1.printStackTrace();
    391         }finally 
    392         {
    393             if (reader != null)
    394             {
    395                 try
    396                 {
    397                     reader.close();
    398                 } catch (IOException e1) 
    399                 {
    400                 }
    401             }
    402         }
    403     }
    404     
    405     /**
    406     * 以行为单位读取文件,常用于读面向行的格式化文件
    407     * @param fileName 文件名
    408     */
    409     public static void readFileByLines(String fileName)
    410     {
    411         File file = new File(fileName);
    412         BufferedReader reader = null;
    413         try
    414         {
    415             System.out.println("以行为单位读取文件内容,一次读一整行:");
    416             reader = new BufferedReader(new FileReader(file));
    417             String tempString = null;
    418             int line = 1;
    419                 //一次读入一行,直到读入null为文件结束
    420             while ((tempString = reader.readLine()) != null)
    421             {
    422                 //显示行号
    423                 System.out.println("line " + line + ": " + tempString);
    424                 line++;
    425             }
    426             reader.close();
    427         } catch (IOException e)
    428         {
    429             e.printStackTrace();
    430         } finally 
    431         {
    432             if (reader != null)
    433             {
    434                 try
    435                 {
    436                     reader.close();
    437                 }catch(IOException e1)
    438                 {
    439                 }
    440             }
    441         }
    442     }
    443     
    444     /**
    445     * 随机读取文件内容
    446     * @param fileName 文件名
    447     */
    448     public static void readFileByRandomAccess(String fileName)
    449     {
    450         RandomAccessFile randomFile = null;
    451         try 
    452         {
    453             System.out.println("随机读取一段文件内容:");
    454             // 打开一个随机访问文件流,按只读方式
    455             randomFile = new RandomAccessFile(fileName, "r");
    456             // 文件长度,字节数
    457             long fileLength = randomFile.length();
    458             // 读文件的起始位置
    459             int beginIndex = (fileLength > 4) ? 4 : 0;
    460             //将读文件的开始位置移到beginIndex位置。
    461             randomFile.seek(beginIndex);
    462             byte[] bytes = new byte[10];
    463             int byteread = 0;
    464             //一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
    465             //将一次读取的字节数赋给byteread
    466             while ((byteread = randomFile.read(bytes)) != -1)
    467             {
    468                 System.out.write(bytes, 0, byteread);
    469             }
    470         } catch (IOException e)
    471         {
    472             e.printStackTrace();
    473         } finally 
    474         {
    475             if (randomFile != null)
    476             {
    477                 try
    478                 {
    479                     randomFile.close();
    480                 } catch (IOException e1)
    481                 {
    482                 }
    483             }
    484         }
    485     }
    486     
    487     /**
    488     * 显示输入流中还剩的字节数
    489     * @param in
    490     */
    491     private static void showAvailableBytes(InputStream in)
    492     {
    493         try 
    494         {
    495             System.out.println("当前字节输入流中的字节数为:" + in.available());
    496         } catch(IOException e) 
    497         {
    498             e.printStackTrace();
    499         }
    500     }
    501     
    502 }
  • 相关阅读:
    团队十日冲刺1
    第八周学习进度
    人月神话阅读笔记02
    课堂练习-顶会热词统计
    第七周学习进度
    《vim — vimrc的设置》
    《开发板 — 调试串口》
    《网络编程 — 127.0.0.1的作用》
    《网络编程 — INADDR_ANY的含义》
    《开发板 — 上查看串口信息》
  • 原文地址:https://www.cnblogs.com/jayceli/p/2446181.html
Copyright © 2020-2023  润新知