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 支持三种文件类型: 文本文件.记录文件 ...
随机推荐
- ANY和SOME 运算符
在SQL中ANY和SOME是同义词,所以下面介绍的时候只使用ANY,SOME的用法和功能和ANY一模一样.和IN运算符不同,ANY必须和其他的比较运算符共同使用,而且必须将比较运算符放在ANY 关键字 ...
- JZYZOJ 1375 双亲数 莫比乌斯反演
http://172.20.6.3/Problem_Show.asp?id=1375 网上搜推理图. 有一段没有写莫比乌斯反演都快忘了..数学能力--,定理完全不会推,但是这道题整体来说应该是比较好写 ...
- Gym - 101620I Intrinsic Interval
题面在这里! 首先一个非常重要的性质是,两个好的区间的交依然是好的区间. 有了这个性质,我们只要找到包含某个区间的右端点最小的好区间,然后就是这个区间的答案拉. 至于找右端点最小的好区间就是一个扫描线 ...
- [xsy2123]毛毛虫
题意:有一棵带点权的树,链修改是把$(x,y)$这条链和与其相邻的节点都加上一个数,查询是问$(x,y)$这条链和与其相邻的节点的权值和 学到了一个新姿势? 考虑树链剖分,在剖重链时每次给当前节点的儿 ...
- 【转载】随机生成k个范围为1-n的随机数,其中有多少个不同的随机数?
来源:http://www.cnblogs.com/haolujun/archive/2012/11/11/2765102.html 假如现在让你随机生成k个范围在1-n内的随机数,那么你能得到多少个 ...
- js流程控制与函数
流程控制 1.条件语句 分支结构 单向分支 if (条件表达式){ code... } 双向分支 if (条件表达式){ code... }else{ code... } 多向分支 if (条件表达式 ...
- Problem G: 十进制数转换为二进制数
#include<stdio.h> int main() { ]; while(scanf("%d",&n)!=EOF) { ; ) { a[i++]=n%; ...
- python的高阶函数
函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数. 高阶函数 定义:一个函数就可以接收另一函数作为参数,这种函数就称之为高阶函数. map/reduce Python ...
- [转]SpringMVC入门
目录 介绍 实例 总结 参考资料 介绍 SpringMVC是一款Web MVC框架. 它跟Struts框架类似,是目前主流的Web MVC框架之一. 本文通过实例来介绍SpringMVC的入门知识. ...
- Manthan, Codefest 16 B. A Trivial Problem 二分 数学
B. A Trivial Problem 题目连接: http://www.codeforces.com/contest/633/problem/B Description Mr. Santa ask ...