• java中读取文件以及向文件中追加数据的总结


      1 package gys;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.File;
      5 import java.io.FileInputStream;
      6 import java.io.FileReader;
      7 import java.io.FileWriter;
      8 import java.io.IOException;
      9 import java.io.InputStream;
     10 import java.io.InputStreamReader;
     11 import java.io.RandomAccessFile;
     12 import java.io.Reader;
     13 
     14 public class ReadFormFile {
     15     /**
     16      * 以字节为单位读取文件,常用语读取二进制文件,如图片,声音,影响等文件.
     17      */
     18     public static void readFileByBytes1(String fileName){
     19         File file=new File(fileName);
     20         InputStream in=null;
     21         try {
     22             System.out.println("以字节为单位读取内容,一次读一个字节:");
     23             //一次读一个字节
     24             in=new FileInputStream(file);
     25             int tempbyte;
     26             while((tempbyte=in.read())!=-1){
     27                 System.out.println(tempbyte);
     28             }
     29             in.close();
     30         }catch(IOException e){
     31             System.out.println("readFileByBytes1异常:IOException.....");
     32             e.printStackTrace();
     33         } catch (Exception e) {
     34             System.out.println("readFileByBytes1异常:Exception.....");
     35             e.printStackTrace();
     36         }
     37     }
     38     /**
     39      * 以字节为单位读取文件,常用语读取二进制文件,如图片,声音,影响等文件.
     40      */
     41     public static void readFileByBytes2(String fileName){
     42         File file=new File(fileName);
     43         InputStream in=null;
     44         try {
     45             System.out.println("以字节为单位读取内容,一次读多个字节");
     46             //一次读多个字节
     47             byte[] tempbytes=new byte[100];
     48             int byteread=0;
     49             in=new FileInputStream(fileName);
     50             ReadFormFile.showAvailableBytes(in);
     51             //读入多个字节到字节数组中,byteread为一次读入的字节数
     52             while((byteread=in.read(tempbytes))!=-1){
     53                 System.out.write(tempbytes,0,byteread);
     54             }
     55         } catch (Exception e) {
     56             System.out.println("readFileByBytes2异常:Exception....");
     57         }finally{
     58             if(in !=null){
     59                 try {
     60                     in.close();
     61                 } catch (Exception e2) {
     62                     // TODO: handle exception
     63                 }
     64             }
     65         }
     66     }
     67     /**
     68      * 以字符为单位读取文件,长用于读取文本,数字类型的文件,一次读取一个字节
     69      */
     70     public static void readFileByChars1(String fileName){
     71         File file=new File(fileName);
     72         Reader reader=null;
     73         try {
     74             System.out.println("以字符为单位,一次读取一个字节");
     75             //一次读一个字符
     76             reader=new InputStreamReader(new FileInputStream(file));
     77             int tempchar;
     78             while((tempchar=reader.read())!=-1){
     79                 //对于windows下,
    这两个字符在一起时,表示一个换行。
     80                 // 但如果这两个字符分开显示时,会换两次行。
     81                 // 因此,屏蔽掉
    ,或者屏蔽
    。否则,将会多出很多空行。
     82                 if((char) tempchar!='
    '){
     83                     System.out.println((char)tempchar);
     84                 }
     85             }
     86             reader.close();
     87         } catch (Exception e) {
     88             e.printStackTrace();
     89         }
     90     }
     91     /**
     92      * 以字符为单位读取文件,长用于读取文本,数字类型的文件,一次读多个字节
     93      */
     94     public static void readFileByChars2(String fileName){
     95         File file = new File(fileName);
     96         Reader reader = null;       
     97         try {
     98             System.out.println("以字符为单位读取文件内容,一次读多个字节:");
     99             // 一次读多个字符
    100             char[] tempchars = new char[30];
    101             int charread = 0;
    102             reader = new InputStreamReader(new FileInputStream(fileName));
    103             // 读入多个字符到字符数组中,charread为一次读取字符数
    104             while ((charread = reader.read(tempchars)) != -1) {
    105                 // 同样屏蔽掉
    不显示
    106                 if ((charread == tempchars.length)
    107                         && (tempchars[tempchars.length - 1] != '
    ')) {
    108                     System.out.print(tempchars);
    109                 } else {
    110                     for (int i = 0; i < charread; i++) {
    111                         if (tempchars[i] == '
    ') {
    112                             continue;
    113                         } else {
    114                             System.out.print(tempchars[i]);
    115                         }
    116                     }
    117                 }
    118             }
    119 
    120         } catch (Exception e1) {
    121             e1.printStackTrace();
    122         } finally {
    123             if (reader != null) {
    124                 try {
    125                     reader.close();
    126                 } catch (IOException e1) {
    127                 }
    128             }
    129         }
    130     }
    131     /**
    132      * 以行为单位读取文件,常用于读面向行的格式化文件
    133      */
    134     public static void readFileByLines(String fileName){
    135         File file=new File(fileName);
    136         BufferedReader reader=null;
    137         try {
    138             System.out.println("以行为单位读取文件内容,一次读取一整行:");
    139             reader=new BufferedReader(new FileReader(file));
    140             String tempString=null;
    141             int line=1;
    142             String result="";
    143             //一次读入一行,直到读入null为文件结束
    144             while((tempString=reader.readLine())!=null){
    145                 //显示行号
    146                 System.out.println("line"+line+":"+tempString);
    147                 //System.out.println(tempString);
    148                 //result+=tempString;
    149                 line++;
    150             }
    151             //System.out.println(result);
    152             reader.close();
    153         }catch(IOException e){
    154             e.printStackTrace();
    155         } finally{
    156             if(reader!=null){
    157                 try {
    158                     reader.close();
    159                 } catch (Exception e2) {
    160                     System.out.println("readFileByLines异常.....");
    161                 }
    162             }
    163         }
    164     }
    165     
    166       /**
    167      * 随机读取文件内容
    168      */
    169     public static void readFileByRandomAccess(String fileName) {
    170         RandomAccessFile randomFile = null;
    171         try {
    172             System.out.println("随机读取一段文件内容:");
    173             // 打开一个随机访问文件流,按只读方式
    174             randomFile = new RandomAccessFile(fileName, "r");
    175             // 文件长度,字节数
    176             long fileLength = randomFile.length();
    177             // 读文件的起始位置
    178             int beginIndex = (fileLength > 4) ? 4 : 0;
    179             // 将读文件的开始位置移到beginIndex位置。
    180             randomFile.seek(beginIndex);
    181             byte[] bytes = new byte[10];
    182             int byteread = 0;
    183             // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
    184             // 将一次读取的字节数赋给byteread
    185             while ((byteread = randomFile.read(bytes)) != -1) {
    186                 System.out.write(bytes, 0, byteread);
    187             }
    188         } catch (IOException e) {
    189             e.printStackTrace();
    190         } finally {
    191             if (randomFile != null) {
    192                 try {
    193                     randomFile.close();
    194                 } catch (IOException e1) {
    195                 }
    196             }
    197         }
    198     }
    199     
    200     /**
    201      * 显示输入流中还剩的字节数
    202      */
    203     private static void showAvailableBytes(InputStream in){
    204         try {
    205             System.out.println("当前输入流中的字节数为:"+in.available());
    206         }catch(IOException e){
    207             System.out.println("showAvailableBytes异常:IOException.....");
    208             e.printStackTrace();
    209         } catch (Exception e) {
    210             System.out.println("showAvailableBytes异常:Exception.....");
    211             e.printStackTrace();
    212         }
    213     }
    214     
    215     /**
    216      *A方法追加文件:使用RandowAccessFile     
    217      */
    218     public static void appendMethodA(String fileName,String content){
    219         try {
    220             //打开一个随机访问文件流,按读写方式
    221             RandomAccessFile randomFile=new RandomAccessFile(fileName,"rw");
    222             //文件长度,字节数
    223             long fileLength=randomFile.length();
    224             //将写文件指针移到文件尾
    225             randomFile.seek(fileLength);
    226             randomFile.writeBytes(content);
    227             randomFile.close();
    228         } catch (IOException e) {
    229             System.out.println("appendMethodA异常....");
    230         }
    231     }
    232     
    233     /**
    234      * B方法追加文件:使用FileWriter
    235      */
    236     public static void appendMethodB(String fileName,String content){
    237         try {            
    238             //打开一个写文件器,构造函数中的第二个参数true表示追加形式写入
    239             FileWriter writer=new FileWriter(fileName,true);
    240             writer.write(content);
    241             writer.close();
    242         } catch (IOException e) {
    243             System.out.println("appendMethodB异常...");
    244         }
    245     }
    246     
    247     
    248 }

    测试代码:

     1 package gys;
     2 
     3 public class Test {
     4     public static void main(String[] args) {
     5         String fileName="f:/a.txt";
     6         String content="new append";
     7         //方法A追加文件
     8         ReadFormFile.appendMethodA(fileName, content);
     9         ReadFormFile.appendMethodA(fileName, "AAAAAAA 
    ");
    10         //显示文件内容
    11         ReadFormFile.readFileByLines(fileName);
    12         //按方法B追加文件
    13         ReadFormFile.appendMethodB(fileName, content);
    14         ReadFormFile.appendMethodB(fileName, "BBBBBBBBBB 
    ");
    15         //显示文件内容
    16         ReadFormFile.readFileByLines(fileName);
    17     }
    18 }

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

  • 相关阅读:
    不装JDK环境运行项目jar包
    java 开发事务回滚
    navicat无法连接MySql; client does not support authentication....
    java url特殊字符报400
    修复windows **.dll缺失
    mysql5.7解压版安装
    IDEA破解
    java 通过request.getParameterMap()获取前台传入参数
    java 实现https请求
    java 实现Http请求
  • 原文地址:https://www.cnblogs.com/guoyansi19900907/p/4595048.html
Copyright © 2020-2023  润新知