java文件读取与写入
package com.myjava; import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; /**
* Created by 14061371 on 2017/5/12.
*/
public class FileUtils {
//获取当前路径 /** 按字节读取
*
* @param fileName
*/
public static void readFileByBytes(String fileName){
File file=new File(fileName);
if(!file.exists()){
return;
}
InputStream in = null;
try {
in = new FileInputStream(file);
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
} /**
* 按字符读取
* @param fileName
*/
public static void readFileByChars(String fileName){
File file=new File(fileName);
if(!file.exists()){
return;
}
Reader reader=null;
try {
reader=new InputStreamReader(new FileInputStream(file));
int tempChart;
char[] tempchars = new char[30];
while((tempChart=reader.read(tempchars))!=-1){
System.out.print(tempchars);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(reader!=null){
try{
reader.close();
}catch (IOException e){ }
}
}
} /**
* 按行读取
* @param fileName
*/
public static void readFileByLines(String fileName){
File file=new File(fileName);
if(!file.exists()){
return;
}
BufferedReader reader=null;
try {
reader=new BufferedReader(new FileReader(file));
String tempString=null;
int line=1;
while((tempString=reader.readLine())!=null){
System.out.println(line+tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(reader!=null){
try{
reader.close();
}catch(IOException e){ }
}
}
} /**
* random读取文件
* @param fileName
*/
public static void readFileByRandomAccess(String fileName){
RandomAccessFile randomFile=null;
try {
randomFile=new RandomAccessFile(fileName,"r");
long fileLength=randomFile.length();
randomFile.seek(0);
byte[] bytes=new byte[10];
int byteread=0;
while((byteread=randomFile.read(bytes))!=-1){
System.out.write(bytes,0,byteread);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e) { }
}
}
} /**
* 读取文件最后N行
*
* 根据换行符判断当前的行数,
* 使用统计来判断当前读取第N行
*
* PS:输出的List是倒叙,需要对List反转输出
*
* @param file 待文件
* @param numRead 读取的行数
* @return List<String>
*/
public static List<String> readLastNLine(File file, long numRead) {
// 定义结果集
List<String> result = new ArrayList<String>();
//行数统计
long count = 0; // 排除不可读状态
if (!file.exists() || file.isDirectory() || !file.canRead()) {
return null;
} // 使用随机读取
RandomAccessFile fileRead = null;
try {
//使用读模式
fileRead = new RandomAccessFile(file, "r");
//读取文件长度
long length = fileRead.length();
//如果是0,代表是空文件,直接返回空结果
if (length == 0L) {
return result;
} else {
//初始化游标
long pos = length - 1;
while (pos > 0) {
pos--;
//开始读取
fileRead.seek(pos);
//如果读取到\n代表是读取到一行
if (fileRead.readByte() == '\n') {
//使用readLine获取当前行
String line = fileRead.readLine();
//保存结果
result.add(line);
//打印当前行
// System.out.println(line);
//行数统计,如果到达了numRead指定的行数,就跳出循环
count++;
if (count == numRead) {
break;
}
}
}
if (pos == 0) {
fileRead.seek(0);
result.add(fileRead.readLine());
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileRead != null) {
try {
//关闭资源
fileRead.close();
} catch (Exception e) {
}
}
}
Collections.reverse(result);
return result;
} /**
* 使用RandomAccessFile追加文件
* @param fileName
*/
public static void appendFileByAccess(String fileName,String content){
try {
RandomAccessFile randomFile=new RandomAccessFile(fileName,"rw");
long fileLength=randomFile.length();
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 使用FileWriter 追加文件内容
* @param fileName
* @param content
*/
public static void appendFile(String fileName,String content){
try {
FileWriter writer=new FileWriter(fileName,true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 往文件头插入数据
* @param filename
* @param pos
* @param insertContent
*/
public static void insert(String filename, int pos, String insertContent){
RandomAccessFile raf=null;
FileOutputStream tmpOut=null;
FileInputStream tmpIn=null;
try{
File tmp = File.createTempFile("tmp", null);
tmp.deleteOnExit();
raf = new RandomAccessFile(filename, "rw");
tmpOut = new FileOutputStream(tmp);
tmpIn = new FileInputStream(tmp);
raf.seek(pos);//首先的话是0
byte[] buf = new byte[64];
int hasRead = 0;
while ((hasRead = raf.read(buf)) > 0) {
//把原有内容读入临时文件
tmpOut.write(buf, 0, hasRead); }
raf.seek(pos);
raf.write(insertContent.getBytes());
//追加临时文件的内容
while ((hasRead = tmpIn.read(buf)) > 0) {
raf.write(buf, 0, hasRead);
}
}catch (IOException e) {
e.printStackTrace();
}finally{
try {
if (raf != null) {
raf.close();
}
if (tmpOut != null) {
tmpOut.close();
}
if (tmpIn != null) {
tmpIn.close();
}
} catch (IOException e) { }
}
}
}
java文件读取与写入的更多相关文章
- Java底层代码实现单文件读取和写入(解决中文乱码问题)
需求: 将"E:/data/车站一次/阿坝藏族羌族自治州.csv"文件中的内容读取,写入到"E:/data//车站一次.csv". 代码: public cla ...
- Apache commons-io实现单文件读取和写入
Apache commons-io提供了很多类,这里只介绍FileUtils类. FileUtils类提供了一些操作文件对象的实用方法,包括文件的读取.写入.复制和比较等. 比如逐句读取和写入一个文件 ...
- python文件读取和写入案例
python文件读取和写入案例 直接上代码吧 都是说明 百度上找了很多,最终得出思路 没有直接可以读取修改的扩展,只能先读取,然后复制一份,然后在复制出来的文件里面追加保存 然后删除读的那个,但是缺 ...
- HDFS数据流-剖析文件读取及写入
HDFS数据流-剖析文件读取及写入 文件读取 1. 客户端通过调用FileSystem对象的open方法来打开希望读取的文件,对于HDFS来说,这个对象是分布式文件系统的一个实例.2. Distrib ...
- JAVA文件读取FileReader
JAVA文件读取FileReader 导包import java.io.FileReader 创建构造方法public FileReader(String filename),参数是文件的路径及文件名 ...
- java===java基础学习(5)---文件读取,写入操作
文件的写入读取有很多方法,今天学到的是Scanner和PrintWriter 文件读取 Scanner in = new Scanner(Paths.get("file.txt") ...
- Java中IO流文件读取、写入和复制
//构造文件File类 File f=new File(fileName); //判断是否为目录 f.isDirectory(); //获取目录下的文件名 String[] fileName=f.li ...
- properties文件读取与写入
将peoperties文件的读取和写入封装成了一个工具类: import java.io.BufferedInputStream; import java.io.FileInputStream; im ...
- Delphi txt文件读取及写入
简介:Delphi支持三种文件类型:文本文件.记录文件.无类型文件.文本文件的读... 在进行win32开发中对文件的读写是最常用的操作之一 Delphi 支持三种文件类型: 文本文件.记录文件 ...
随机推荐
- RabbitMQ (九) 消息的参数详解
上篇文章讲了声明一个队列时的参数设置,这篇文章主要说一说发布消息时的参数设置. 发布消息时的完整入参是这样的: channel.BasicPublish ( exchange: "test_ ...
- EasyUI学习总结(一)——EasyUI入门(转载)
本文转载自:http://www.cnblogs.com/xdp-gacl/p/4075079.html 一.EasyUI下载 EasyUI官方下载地址:http://www.jeasyui.com/ ...
- 【二项式定理】【推导】计蒜客17115 2017 ACM-ICPC 亚洲区(西安赛区)网络赛 B. Coin
题意:投一枚硬币向上的概率是q/p.问你投K枚硬币,向上的枚数为偶数枚的概率是? 要求的即为. 这个东西是个二项展开式的偶数项系数和,来,我们复习一下高中数学,设f(x)=(ax+b)^n,则其偶数项 ...
- Perl正则表达式
perl正则表达式就是通过一串特别设计的字符串,可以按照我们的需求匹配.替换.转化目标字符串.本文主要是对一些常用的正则表达以及语法的总结以及举例,供广大喜爱Perl的同学交流学习. 操作符: =~ ...
- [DesignPattern]Builder设计模式
模式的定义 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示. 模式的使用场景 相同的方法,不同的执行顺序,产生不同的事件结果时: 多个部件或零件,都可以装配到一个对象中,但是 ...
- php读取超大文件fseek
function readMaxFile($fp , $start = 0) { $tag = "\n"; $i = 0; $content = ''; while($i < ...
- Educational Codeforces Round 8 C. Bear and String Distance 贪心
C. Bear and String Distance 题目连接: http://www.codeforces.com/contest/628/problem/C Description Limak ...
- 从connect到express01-connect
介绍 Connect是一个node中间件框架.每个中间件在http处理过程中通过改写request, response的数据.状态,实现了特定的功能. 根据中间件在整个http处理流程的位置,将中间件 ...
- mongo 实时同步工具 mongosync
文档地址:https://github.com/Qihoo360/mongosync/wiki/%E4%BD%BF%E7%94%A8%E6%A0%B7%E4%BE%8B #数据全量备份mongodum ...
- SQLAlchemy使用笔记--SQLAlchemy ORM(二)
參考: http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html#building-a-relationship http://docs.sqla ...