文件读写操作

  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 import java.io.LineNumberReader;
  8 import java.text.SimpleDateFormat;
  9 import java.util.Date;
 10 
 11 /**
 12  * 这是一个与日志读写有关的类,定义了一些通用的方法
 13  *
 14  * @author Devon
 15  *
 16  */
 17 public class LogReaderWriter {
 18     
 19     public static int getTotalLines(String fileName) throws IOException {
 20         FileReader in = new FileReader(fileName);
 21         LineNumberReader reader = new LineNumberReader(in);
 22         String strLine = reader.readLine();
 23         int totalLines = 0;
 24         while (strLine != null) {
 25             totalLines++;
 26             strLine = reader.readLine();
 27         }
 28         reader.close();
 29         in.close();
 30         return totalLines;
 31     }
 32 
 33     public static void readForPage(String filePath, int pageNo, int pageSize) throws IOException {
 34         File file = new File(filePath);
 35         FileReader in = new FileReader(file);
 36         LineNumberReader reader = new LineNumberReader(in);
 37         String s = "";
 38         /*if (lineNumber <= 0 || lineNumber > getTotalLines(sourceFile)) {  
 39          System.out.println("不在文件的行数范围(1至总行数)之内。");  
 40          System.exit(0);  
 41          }  */
 42         int startRow = (pageNo - 1) * pageSize + 1;
 43         int endRow = pageNo * pageSize;
 44         int lines = 0;
 45         System.out.println("startRow:" + startRow);
 46         System.out.println("endRow:" + endRow);
 47         while (s != null) {
 48             lines++;
 49             s = reader.readLine();
 50             if (lines >= startRow && lines <= endRow) {
 51                 System.out.println("line:" + lines + ":" + s);
 52             }
 53         }
 54         reader.close();
 55         in.close();
 56     }
 57 
 58     /**
 59      *
 60      * @param filePath 文件路径的字符串表示形式
 61      * @param KeyWords 查找包含某个关键字的信息:非null为带关键字查询;null为全文显示
 62      * @return 当文件存在时,返回字符串;当文件不存在时,返回null
 63      */
 64     public static String readFromFile(String filePath, String KeyWords) {
 65         StringBuffer stringBuffer = null;
 66         File file = new File(filePath);
 67         if (file.exists()) {
 68             stringBuffer = new StringBuffer();
 69             FileReader fileReader = null;
 70             BufferedReader bufferedReader = null;
 71             String temp;
 72             try {
 73                 fileReader = new FileReader(file);
 74                 bufferedReader = new BufferedReader(fileReader);
 75                 while ((temp = bufferedReader.readLine()) != null) {
 76                     if (KeyWords == null) {
 77                         stringBuffer.append(temp).append("\n");
 78                     } else {
 79                         if (temp.contains(KeyWords)) {
 80                             stringBuffer.append(temp).append("\n");
 81                         }
 82                     }
 83                 }
 84             } catch (FileNotFoundException e) {
 85                 //e.printStackTrace();
 86             } catch (IOException e) {
 87                 //e.printStackTrace();
 88             } finally {
 89                 try {
 90                     if (fileReader != null) {
 91                         fileReader.close();
 92                     }
 93                 } catch (IOException e) {
 94                     //e.printStackTrace();
 95                 }
 96                 try {
 97                     if (bufferedReader != null) {
 98                         bufferedReader.close();
 99                     }
100                 } catch (IOException e) {
101                     //e.printStackTrace();
102                 }
103             }
104         }
105         if (stringBuffer == null) {
106             return null;
107         } else {
108             return stringBuffer.toString();
109         }
110 
111     }
112 
113     /**
114      * 将指定字符串写入文件。如果给定的文件路径不存在,将新建文件后写入。
115      *
116      * @param log 要写入文件的字符串
117      * @param filePath 文件路径的字符串表示形式,目录的层次分隔可以是“/”也可以是“\\”
118      * @param isAppend true:追加到文件的末尾;false:以覆盖原文件的方式写入
119      * @return 文件是否写入成功
120      */
121     public static boolean writeIntoFile(String log, String filePath, boolean isAppend) {
122         boolean isSuccess = true;
123         File file = new File(filePath);
124         if (!file.exists()) {
125             createNewFile(filePath);
126         }
127         //将logs写入文件
128         FileWriter fileWriter = null;
129         try {
130             fileWriter = new FileWriter(file, isAppend);
131             fileWriter.write(log + "\n");
132             fileWriter.flush();
133         } catch (IOException e) {
134             isSuccess = false;
135             //e.printStackTrace();
136         } finally {
137             try {
138                 if (fileWriter != null) {
139                     fileWriter.close();
140                 }
141             } catch (IOException e) {
142                 //e.printStackTrace();
143             }
144         }
145 
146         return isSuccess;
147     }
148 
149     /**
150      * 创建文件,如果该文件已存在将不再创建(即不起任何作用)
151      *
152      * @param filePath 要创建文件的路径的字符串表示形式,目录的层次分隔可以是“/”也可以是“\\”
153      * @return 创建成功将返回true;创建不成功则返回false
154      */
155     public static boolean createNewFile(String filePath) {
156         boolean isSuccess;
157         //创建文件
158         File file = new File(filePath);
159         try {
160             isSuccess = file.createNewFile();
161         } catch (IOException e) {
162             isSuccess = false;
163         }
164         return isSuccess;
165     }
166 
167     public static void main(String[] args) {
168         String filename = "b.txt";
169         
170         String str;
171         for (int i = 0; i < 100; i++) {
172             str = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + " - 插入数据" + i;
173             writeIntoFile(str, filename, true);
174         }
175         
176         try {
177             long time = System.currentTimeMillis();
178             int count = getTotalLines(filename);
179             System.out.println(System.currentTimeMillis() - time);
180             
181             System.out.println("当前文件总行数: " + count);
182             readForPage(filename, 10, 10);
183         } catch (IOException ex) {
184            ex.printStackTrace();
185         }
186     }
187 }

 

转载于:https://www.cnblogs.com/qixin622/p/6680973.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值