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文件读取与写入的更多相关文章

  1. Java底层代码实现单文件读取和写入(解决中文乱码问题)

    需求: 将"E:/data/车站一次/阿坝藏族羌族自治州.csv"文件中的内容读取,写入到"E:/data//车站一次.csv". 代码: public cla ...

  2. Apache commons-io实现单文件读取和写入

    Apache commons-io提供了很多类,这里只介绍FileUtils类. FileUtils类提供了一些操作文件对象的实用方法,包括文件的读取.写入.复制和比较等. 比如逐句读取和写入一个文件 ...

  3. python文件读取和写入案例

    python文件读取和写入案例  直接上代码吧 都是说明 百度上找了很多,最终得出思路 没有直接可以读取修改的扩展,只能先读取,然后复制一份,然后在复制出来的文件里面追加保存 然后删除读的那个,但是缺 ...

  4. HDFS数据流-剖析文件读取及写入

    HDFS数据流-剖析文件读取及写入 文件读取 1. 客户端通过调用FileSystem对象的open方法来打开希望读取的文件,对于HDFS来说,这个对象是分布式文件系统的一个实例.2. Distrib ...

  5. JAVA文件读取FileReader

    JAVA文件读取FileReader 导包import java.io.FileReader 创建构造方法public FileReader(String filename),参数是文件的路径及文件名 ...

  6. java===java基础学习(5)---文件读取,写入操作

    文件的写入读取有很多方法,今天学到的是Scanner和PrintWriter 文件读取 Scanner in = new Scanner(Paths.get("file.txt") ...

  7. Java中IO流文件读取、写入和复制

    //构造文件File类 File f=new File(fileName); //判断是否为目录 f.isDirectory(); //获取目录下的文件名 String[] fileName=f.li ...

  8. properties文件读取与写入

    将peoperties文件的读取和写入封装成了一个工具类: import java.io.BufferedInputStream; import java.io.FileInputStream; im ...

  9. Delphi txt文件读取及写入

    简介:Delphi支持三种文件类型:文本文件.记录文件.无类型文件.文本文件的读...   在进行win32开发中对文件的读写是最常用的操作之一 Delphi 支持三种文件类型:  文本文件.记录文件 ...

随机推荐

  1. 算法练习(js)

    1. 问题:Spinal Tap Case 将字符串转换为 spinal case.Spinal case 是 all-lowercase-words-joined-by-dashes 这种形式的,也 ...

  2. smail修改字符串 汉字

    韩梦飞沙 yue31313 韩亚飞 han_meng_fei_sha  313134555@qq.com 将smali文件中的unicode字符串变为汉字

  3. Codeforces #447 Div.2 Tutorial

    Problem A:QAQ 给一个字符串,求出可非连续的QAQ序列有多少个. Analysis:比较水的一道题,记录每一个Q的位置,预处理A的个数即可 然而还是fst了,原因是未考虑一个Q都没有的极端 ...

  4. 【推导】【暴力】Codeforces Round #432 (Div. 2, based on IndiaHacks Final Round 2017) C. Five Dimensional Points

    题意:给你五维空间内n个点,问你有多少个点不是坏点. 坏点定义:如果对于某个点A,存在点B,C,使得角BAC为锐角,那么A是坏点. 结论:如果n维空间内已经存在2*n+1个点,那么再往里面添加任意多个 ...

  5. Linux下KVM的图形界面管理工具(WebVirtMgr)(Web版)

    WebVirtMgr面板 截图 介绍 WebVirtMgr是一个基于libvirt的Web界面,用于管理虚拟机.它允许您创建和配置新域,并调整域的资源分配.VNC查看器为来宾域提供完整的图形控制台.K ...

  6. WPF的UI虚拟化

    许多时候,我们的界面上会呈现大量的数据,如包含数千条记录的表格或包含数百张照片的相册.由于呈现UI是一件开销比较大的动作,一次性呈现数百张照片就目前的电脑性能来说是需要占用大量内存和时间的.因此需要对 ...

  7. HDU 2389 Rain on your Parade(二分匹配,Hopcroft-Carp算法)

    Rain on your Parade Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 655350/165535 K (Java/Ot ...

  8. [Eclipse插件] 安装和使用JD-Eclipse插件

    JD-Core 是一个免费的库,从一个或多个“.class”文件中 重构Java源代码.JD-Core可以用来恢复丢失的源代码,并深究Java运行时类库.支持Java 5的功能:如注释,泛型或键入“枚 ...

  9. 关于weblogic server对docker的支持

    Docker是目前比较热门的一个技术话题,WebLogic Server从12.1.3版本支持Docker,但对于操作系统和内核有一定的要求,具体参考下表 我曾在ubuntu,Oracle Enter ...

  10. ubuntu安装elasticSearch及插件

    原文地址:http://www.niu12.com/article/18 前提 1.安装好Java1.8以上环境并配置好JAVA_HOME(elasticsearch运行环境) 2.node环境6.5 ...