文件读写操作

  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 }
时间: 2024-08-08 10:07:16

文件读写操作的相关文章

java文件读写操作类

借鉴了项目以前的文件写入功能,实现了对文件读写操作的封装 仅仅需要在读写方法传入路径即可(可以是绝对或相对路径) 以后使用时,可以在此基础上改进,比如: 写操作: 1,对java GUI中文本框中的内容进行捕获,放在txt文本文档中 2,对各种类型数据都以字符串的形式逐行写入 3,对全局数组的内容进行写入 读操作: 获取文件行数 对逐行字符串型数据进行类型转换,放入二维数组中 为后面算法处理提供入口,但是要小心的是:不可以将行数用全局变量做计数器,否则每次读入是全局变量累加出错,应重新开始读取

php学习基础-文件系统(二) 文件读写操作、文件资源处理

一.文件的打开与关闭 /* *读取文件中的内容 * file_get_contents(); //php5以上 * file() * readfile(); * * 不足:全部读取, 不能读取部分,也不能指定的区域 * * fopen() * fread() * fgetc() * fgets() * * * * * 写入文件 * file_put_contents("URL", "内容字符串"); //php5以上 * 如果文件不存在,则创建,并写入内容 * 如果

Python常用的文件读写操作和字符串操作

文件读写操作 fileUtils.py # -*- coding: utf-8 -*- import os def getFileList(dir, fileList=[]):     """     遍历一个目录,输出所有文件名     param dir: 待遍历的文件夹     param filrList : 保存文件名的列表     return fileList: 文件名列表     """     newDir = dir     

Android数据存储——文件读写操作(File)

Android文件读写操作 一.文件的基本操作 Android中可以在设备本身的存储设备或外接的存储设备中创建用于保存数据的文件.在默认状态下,文件是不能在不同程序间共享的. 当用户卸载您的应用程序时,这些文件删除. 文件存储数据可以通过openFileOutput方法打开一个文件(如果这个)文件不存在就自动创建这个文件),通过load方法来获取文件中的 数据,通过deleteFile方法删除一个指定的文件. 1,常用方法介绍: File是通过FileInputStream和FileOutput

python进阶--文件读写操作

Python读写文件 1. open 使用open打开文件后一定要记得调用 文件对象的close()方法.比如可以用try --finally语句来确保最后能关闭文件. >>>f1 = open('thisfile.txt') >>>try: f1.read() finally: f1.close() 2. 读文件(read,readline,readlines) ①读文本文件 input = open('data','r') input.read() ②读二进制文件

C文件读写操作

C语言的文件 一.文件基本操作:        在c语言中,对数据文件的操作都是依靠文件类型指针来完成. 1.文件类型指针的定义方式:FILE *文件类型变量 2.调用fopen函数打开文件的方法: 文件类型指针变量=fopen(文件名,使用文件打开方式): 文件打开方式(12种) 文件打开方式 意义 rt 只读打开一个文本文件,只允许读数据 wt 只写打开或建立一个文本文件,只允许写数据 at 追加打开一个文本文件,并在文件末尾写数据 rb 只读打开一个二进制文件,只允许读数据 wb 只写打开

C语言文件读写操作,从文件读取数据

很早写的在linux系统下的文件读写操作,从文件中读取数据 #include <stdio.h> int ReadInfoFromFile(const char *strFile) { FILE *fp; char ch; fp = fopen(strFile, "r"); // 只读的方式打开文件 if(fp==NULL) { perror("fopen"); // 打开文件失败 打印错误信息 return -1; } ch = fgetc(fp);

【python学习笔记】pthon3.x中的文件读写操作

在学习python文件读写的时候,因为教程是针对python2的,而使用的是python3.想要利用file类时,类库里找不到,重装了python2还是使不了.在别人园子认真拜读了<详解python2和python3区别>(已收藏)之后,才发现python3已经去掉file类. 现在利用python进行文件读写的方法更加类似于C语言的文件读写操作. 如今总结如下: 一 打开文件—— f = open('poem.txt','x+'): 读过open的帮助文档,然后自己翻译了一下,现给大家分享一

python(三)一个文件读写操作的小程序

我们要实现一个文件读写操作的小程序 首先我们有一个文件 我们要以"============"为界限,每一个角色分割成一个独立的txt文件,按照分割线走的话是分成 xiaoNa_1.txt xiaoBing_1.txt xiaoNa_2.txt xiaoBing_2.txt 这样格式的四个文件 下面上代码: #定义一个保存文件的函数 def save_file(xiaoNa,xiaoBing,count): file_name_xiaoBing = 'xiaoBing_'+str(cou

C语言文件读写操作,写入数据到文件

很早写的在linux系统下的文件读写操作,写入数据到文件,很时候初学者学习 #include <stdio.h> int writeInfoToFile(const char *strFile) { int age, i; char name[10]; FILE *fp; fp = fopen(strFile, "w"); // 只读的方式打开文件 if(fp == NULL) { perror("fopen"); // 文件打开失败,打印错误信息 re