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 支持三种文件类型: 文本文件.记录文件 ...
随机推荐
- Mac下配置PHP支持GD库FreeType
一句话脚本 curl -s http://php-osx.liip.ch/install.sh | bash -s 5.6 记得要FQ哦. 或者下面代码保存成.sh ,代码从http://php-os ...
- 【BZOJ 1078】 1078: [SCOI2008]斜堆
1078: [SCOI2008]斜堆 Description 斜堆(skew heap)是一种常用的数据结构.它也是二叉树,且满足与二叉堆相同的堆性质:每个非根结点的值都比它父亲大.因此在整棵斜堆中, ...
- [BZOJ4246]两个人的星座(计算几何)
4246: 两个人的星座 Time Limit: 40 Sec Memory Limit: 256 MBSubmit: 101 Solved: 55[Submit][Status][Discuss ...
- BZOJ 3571 [Hnoi2014]画框(最小乘积完美匹配)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3571 [题目大意] 给出一张二分图,每条边上有a,b两个值,求完美匹配, 使得suma ...
- 【数论】【莫比乌斯反演】【线性筛】bzoj2301 [HAOI2011]Problem b
对于给出的n个询问,每次求有多少个数对(x,y),满足a≤x≤b,c≤y≤d,且gcd(x,y) = k,gcd(x,y)函数为x和y的最大公约数. 100%的数据满足:1≤n≤50000,1≤a≤b ...
- 【虚树】hdu6161 Big binary tree
题意:一棵n个结点的完全二叉树,初始i号结点的权值为i.有两种操作:单点修改:询问经过某个结点的路径中,权值和最大的路径的权值和是多少. 修改的时候,暴力修改到根节点的路径上的点的f(x)即可. 跟虚 ...
- java笔记之面向对象
一.面向过程与面向对象的区别 1 面向过程:主要关注点是:实现的具体过程,因果关系[集成显卡的开发思路] * 优点:对于业务逻辑比较简单的程序,可以达到快速开发,前期投入成本较低. * 缺点:采用面向 ...
- codevs 1345 饥饿的奶牛
1345 饥饿的奶牛 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold 题目描述 Description John养了若干奶牛,每天晚上奶牛都要进食.由于条件比较 ...
- Codeforces Round #339 (Div. 1) B. Skills 暴力 二分
B. Skills 题目连接: http://www.codeforces.com/contest/613/problem/B Description Lesha plays the recently ...
- <摘录>Linux 环境下编译 0.11版本内核 kernel
系统环境:Fedora 13 + gcc-4.4.5 最近在看<linux内核0.11完全注释>一书,由于书中涉及汇编语言的地方众多,本人在大学时汇编语言学得一塌糊涂,所以实在看不下去了, ...