zoukankan      html  css  js  c++  java
  • Java读取文件方法和给文件追加内容

    本文转载自:http://www.cnblogs.com/lovebread/archive/2009/11/23/1609122.html

    1、按字节读取文件内容
    2、按字符读取文件内容
    3、按行读取文件内容
    4、随机读取文件内容

    5.找到文件中指定的内容,并保存到一个新文件中(本例子是操作的QQ导出来的群消息)

    ReadFromFileUtil.java

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

    5.将内容追加到文件尾部

    AppendToFileUtil.java

     1 import java.io.FileWriter;
     2 import java.io.IOException;
     3 import java.io.RandomAccessFile;
     4 
     5 public class AppendToFileUtil {
     6     /**
     7      * A方法追加文件:使用RandomAccessFile
     8      */
     9     public static void appendMethodA(String fileName, String content) {
    10         try {
    11             // 打开一个随机访问文件流,按读写方式
    12             RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
    13             // 文件长度,字节数
    14             long fileLength = randomFile.length();
    15             //将写文件指针移到文件尾。
    16             randomFile.seek(fileLength);
    17             randomFile.writeBytes(content);
    18             randomFile.close();
    19         } catch (IOException e) {
    20             e.printStackTrace();
    21         }
    22     }
    23 
    24     /**
    25      * B方法追加文件:使用FileWriter
    26      */
    27     public static void appendMethodB(String fileName, String content) {
    28         try {
    29             //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
    30             FileWriter writer = new FileWriter(fileName, true);
    31             writer.write(content);
    32             writer.close();
    33         } catch (IOException e) {
    34             e.printStackTrace();
    35         }
    36     }
    37 
    38     public static void main(String[] args) {
    39         String fileName = "D:/output.txt";
    40         String content = "new append!";
    41         //按方法A追加文件  使用RandomAccessFile
    42         appendMethodA(fileName, content);
    43         appendMethodA(fileName, "append end. 
    ");
    44         //显示文件内容
    45         ReadFromFile.readFileByLines(fileName);
    46         //按方法B追加文件
    47         appendMethodB(fileName, content);
    48         appendMethodB(fileName, "append end. 
    ");
    49         //显示文件内容
    50         ReadFromFile.readFileByLines(fileName);
    51     }
    52 }

    6.操作文件,找到特定的内容导出到另一个文件中

     1 import java.io.BufferedReader;
     2 import java.io.File;
     3 import java.io.FileNotFoundException;
     4 import java.io.FileReader;
     5 import java.io.FileWriter;
     6 import java.io.IOException;
     7 
     8 public class GroupMessageFileHandle {
     9     public static void main(String[] args) {
    10         File sourceFile = new File("C:\Users\ABC\Desktop\【媒体运营研发部】.txt");
    11         File newFile = new File("C:\Users\ABC\Desktop\刘磊说.txt");
    12         readFileByLines(sourceFile,    "刘磊(26563956)", newFile);
    13     }
    14 
    15     /**
    16      * 以行为单位读取文件,常用于读面向行的格式化文件
    17      */
    18     public static void readFileByLines(File sourceFile, String targetName,
    19             File newFile) {
    20         BufferedReader sourceFileReader = null;
    21         BufferedReader newFileReader = null;
    22         
    23         //校验目标文件
    24         if (newFile.exists() && newFile.isFile()) {
    25             System.out.println("使用已经存在的newFile.txt文件");
    26         } else {
    27             try {
    28                 // 创建文件
    29                 newFile.createNewFile();
    30                 System.out.println("创建newFile.txt文件");
    31             } catch (IOException e) {
    32                 System.out.println("创建newFile.txt文件失败,错误信息:"+ e.getMessage());
    33                 return;
    34             }
    35         }
    36         
    37         try {
    38             System.out.println("以行为单位读取文件内容,一次读一整行:");
    39             sourceFileReader = new BufferedReader(new FileReader(sourceFile));
    40             String tempString = null;
    41             int line = 1;
    42 
    43             newFileReader = new BufferedReader(new FileReader(newFile));
    44             FileWriter fileWriter = new FileWriter(newFile);
    45             
    46             // 一次读入一行,直到读入null为文件结束            
    47             while ((tempString = sourceFileReader.readLine()) != null) {
    48                 if (tempString.contains(targetName)) {
    49                     // 下面开始向文件中写入数据
    50                     try {
    51                         if(newFileReader.readLine() != null){
    52                             //向文件中追加内容
    53                             fileWriter.append(tempString);
    54                             fileWriter.append("
    ");
    55                         }else{//文件第一次写入数据
    56                             fileWriter.write(tempString);
    57                             fileWriter.append("
    ");
    58                         }
    59                         
    60                         
    61                         String nextLine = sourceFileReader.readLine();
    62                         while(nextLine != null && !nextLine.contains("201")){
    63                             fileWriter.append(nextLine);
    64                             fileWriter.append("
    ");
    65                             nextLine = sourceFileReader.readLine();
    66                         }
    67                         
    68                         fileWriter.append("
    ");
    69                     } catch (FileNotFoundException e) {
    70                         System.out.println("找不到文件!错误信息为:" + e.getMessage());
    71                     }
    72                 }
    73                 // 显示行号
    74                 line++;
    75             }
    76             fileWriter.close();
    77             sourceFileReader.close();
    78             newFileReader.close();
    79         } catch (IOException e) {
    80             e.printStackTrace();
    81         } finally {
    82             if (sourceFileReader != null) {
    83                 try {
    84                     sourceFileReader.close();
    85                 } catch (IOException e1) {
    86                 }
    87             }
    88             if (newFileReader != null) {
    89                 try {
    90                     newFileReader.close();
    91                 } catch (IOException e1) {
    92                 }
    93             }
    94         }
    95     }
    96 }
  • 相关阅读:
    Django基础(一)
    CSS
    HTML
    python之路_面向对象
    python之路第六篇
    python之路第四篇
    python之路第三篇
    python之路第二篇
    python之路第一篇
    hdu 3551(一般图的匹配)
  • 原文地址:https://www.cnblogs.com/DreamDrive/p/5738277.html
Copyright © 2011-2022 走看看