干Java这么久,一直在做WEB相关的项目,一些基础类差不多都已经忘记。经常想得捡起,但总是因为一些原因,不能如愿。

其实不是没有时间,只是有些时候疲于总结,今得空,下定决心将丢掉的都给捡起来。

文件读写是一个在项目中经常遇到的工作,有些时候是因为维护,有些时候是新功能开发。我们的任务总是很重,工作节奏很快,快到我们不能停下脚步去总结。

文件读写有以下几种常用的方法

1、字节读写(InputStream/OutputStream)

2、字符读取(FileReader/FileWriter)

3、行读取(BufferedReader/BufferedWriter)

代码(以读取为例):

复制代码
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
/**
* <b>文件读取类</b><br />
* 1、按字节读取文件内容<br />
* 2、按字符读取文件内容<br />
* 3、按行读取文件内容<br />
* @author qin_xijuan
*
*/
public class FileOperate {

private static final String FILE_PATH = "d:/work/the List of Beautiful Music.txt";

/**
* 以字节为单位读取文件内容
* @param filePath:需要读取的文件路径
*/
public static void readFileByByte(String filePath) {
File file = new File(filePath);
// InputStream:此抽象类是表示字节输入流的所有类的超类。
InputStream ins = null ;
try{
// FileInputStream:从文件系统中的某个文件中获得输入字节。
ins = new FileInputStream(file);
int temp ;
// read():从输入流中读取数据的下一个字节。
while((temp = ins.read())!=-1){
System.out.write(temp);
}
}catch(Exception e){
e.getStackTrace();
}finally{
if (ins != null){
try{
ins.close();
}catch(IOException e){
e.getStackTrace();
}
}
}
}

/**
* 以字符为单位读取文件内容
* @param filePath
*/
public static void readFileByCharacter(String filePath){
File file = new File(filePath);
// FileReader:用来读取字符文件的便捷类。
FileReader reader = null;
try{
reader = new FileReader(file);
int temp ;
while((temp = reader.read()) != -1){
if (((char) temp) != '\r') {
System.out.print((char) temp);
}
}
}catch(IOException e){
e.getStackTrace();
}finally{
if (reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* 以行为单位读取文件内容
* @param filePath
*/
public static void readFileByLine(String filePath){
File file = new File(filePath);
// BufferedReader:从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
BufferedReader buf = null;
try{
// FileReader:用来读取字符文件的便捷类。
buf = new BufferedReader(new FileReader(file));
// buf = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String temp = null ;
while ((temp = buf.readLine()) != null ){
System.out.println(temp);
}
}catch(Exception e){
e.getStackTrace();
}finally{
if(buf != null){
try{
buf.close();
} catch (IOException e) {
e.getStackTrace();
}
}
}
}

public static void main(String args[]) {
readFileByByte(FILE_PATH);
readFileByCharacter(FILE_PATH);
readFileByLine(FILE_PATH);
}
}
复制代码
// ----------------------------------------------------------------- 分割线 -----------------------------------------------------------------------------

再经过两位同行的提点下,我对之前写的文件做了点修改,并通过读写一个1.2M的文本文件来测试各方法的性能。从多次测试结果来看,行读写却是是Java.nio更有效率。

经过修改之后的代码如下:

复制代码
package com.waddell.basic;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
* <b>文件读取类</b><br />
* 1、按字节读取文件内容<br />
* 2、按字符读取文件内容<br />
* 3、按行读取文件内容<br />
*
* @author qin_xijuan
*
*/
public class FileOperate {

private static final String FILE_PATH = "d:/work/jipinwodi.txt";

/**
* 以字节为单位读写文件内容
*
* @param filePath
* :需要读取的文件路径
*/
public static void readFileByByte(String filePath) {
File file = new File(filePath);
// InputStream:此抽象类是表示字节输入流的所有类的超类。
InputStream ins = null;
OutputStream outs = null;
try {
// FileInputStream:从文件系统中的某个文件中获得输入字节。
ins = new FileInputStream(file);
outs = new FileOutputStream("d:/work/readFileByByte.txt");
int temp;
// read():从输入流中读取数据的下一个字节。
while ((temp = ins.read()) != -1) {
outs.write(temp);
}
} catch (Exception e) {
e.getStackTrace();
} finally {
if (ins != null && outs != null) {
try {
outs.close();
ins.close();
} catch (IOException e) {
e.getStackTrace();
}
}
}
}

/**
* 以字符为单位读写文件内容
*
* @param filePath
*/
public static void readFileByCharacter(String filePath) {
File file = new File(filePath);
// FileReader:用来读取字符文件的便捷类。
FileReader reader = null;
FileWriter writer = null;
try {
reader = new FileReader(file);
writer = new FileWriter("d:/work/readFileByCharacter.txt");
int temp;
while ((temp = reader.read()) != -1) {
writer.write((char)temp);
}
} catch (IOException e) {
e.getStackTrace();
} finally {
if (reader != null && writer != null) {
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* 以行为单位读写文件内容
*
* @param filePath
*/
public static void readFileByLine(String filePath) {
File file = new File(filePath);
// BufferedReader:从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
BufferedReader bufReader = null;
BufferedWriter bufWriter = null;
try {
// FileReader:用来读取字符文件的便捷类。
bufReader = new BufferedReader(new FileReader(file));
bufWriter = new BufferedWriter(new FileWriter("d:/work/readFileByLine.txt"));
// buf = new BufferedReader(new InputStreamReader(new
// FileInputStream(file)));
String temp = null;
while ((temp = bufReader.readLine()) != null) {
bufWriter.write(temp+"\n");
}
} catch (Exception e) {
e.getStackTrace();
} finally {
if (bufReader != null && bufWriter != null) {
try {
bufReader.close();
bufWriter.close();
} catch (IOException e) {
e.getStackTrace();
}
}
}
}

/**
* 使用Java.nio ByteBuffer字节将一个文件输出至另一文件
*
* @param filePath
*/
public static void readFileByBybeBuffer(String filePath) {
FileInputStream in = null;
FileOutputStream out = null;
try {
// 获取源文件和目标文件的输入输出流
in = new FileInputStream(filePath);
out = new FileOutputStream("d:/work/readFileByBybeBuffer.txt");
// 获取输入输出通道
FileChannel fcIn = in.getChannel();
FileChannel fcOut = out.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
// clear方法重设缓冲区,使它可以接受读入的数据
buffer.clear();
// 从输入通道中将数据读到缓冲区
int r = fcIn.read(buffer);
if (r == -1) {
break;
}
// flip方法让缓冲区可以将新读入的数据写入另一个通道
buffer.flip();
fcOut.write(buffer);
}

} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null && out != null) {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static long getTime(){
return System.currentTimeMillis();
}

public static void main(String args[]) {
long time1 = getTime() ;
// readFileByByte(FILE_PATH);// 8734,8281,8000,7781,8047
// readFileByCharacter(FILE_PATH);// 734, 437, 437, 438, 422
// readFileByLine(FILE_PATH);// 110, 94, 94, 110, 93
readFileByBybeBuffer(FILE_PATH);// 125, 78, 62, 78, 62
long time2 = getTime() ;
System.out.println(time2-time1);
}
}
复制代码
在main方法中,调用各方法之后,有五组数据,分辨是我5次读写文件测试出来的时间(毫秒)。

关于Java.nio 请参考:http://www.iteye.com/topic/834447

转:Java读写文件各种方法及性能比较的更多相关文章

  1. Java读写文件方法总结

    Java读写文件方法总结 Java的读写文件方法在工作中相信有很多的用处的,本人在之前包括现在都在使用Java的读写文件方法来处理数据方面的输入输出,确实很方便.奈何我的记性实在是叫人着急,很多时候既 ...

  2. java读写文件大全

     java读写文件大全 最初java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类,这两个类都是抽象类,Writer中 write(char[] ch,int o ...

  3. C#读写文件的方法汇总_C#教程_脚本之家

    C#读写文件的方法汇总_C#教程_脚本之家 http://www.jb51.net/article/34936.htm

  4. Java读写文件的几种方式

    自工作以后好久没有整理Java的基础知识了.趁有时间,整理一下Java文件操作的几种方式.无论哪种编程语言,文件读写操作时避免不了的一件事情,Java也不例外.Java读写文件一般是通过字节.字符和行 ...

  5. 【java】java 读写文件

    场景:JDK8  将上传的文件,保存到服务器 Java读写文件操作: MultipartFile file InputStream inputStream = file.getInputStream( ...

  6. 【转】Java读写文件大全

    使用Java操作文本文件的方法详解        最初java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类,这两个类都是抽象类,Writer中 write(ch ...

  7. java 读写文件常用方法

    package study.bigdata; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; ...

  8. java读写文件IO

    package Common.readFile; import Common.tool.User; import com.fasterxml.jackson.databind.ObjectMapper ...

  9. Java读写文件常用方法

    一.字符流:读写纯文本(txt,csv等), 1 字符流写文件主要用:FileWriter,BufferedWriter,PrintWriter 1.1 测试 FileWriter 写入 privat ...

随机推荐

  1. 【codeforces 257D】Sum

    [题目链接]:http://codeforces.com/problemset/problem/257/D [题意] 给你n个数字; 这n个数字组成的数组满足: a[i-1]<=a[i]< ...

  2. IntelliJ IDEA 进行Maven项目创建build

    IntelliJ IDEA 进行Maven项目创建build 1,文件-新建-maven 项目:2,编写pom.xml文件:3,鼠标放到左下,然后选择Maven Projects,然后可以查看项目信息 ...

  3. 死锁的Dump文件

    死锁的Dump文件 package com.stono.thread; public class DeadLockDemo { private static String A = "A&qu ...

  4. [MST] Loading Data from the Server using lifecycle hook

    Let's stop hardcoding our initial state and fetch it from the server instead. In this lesson you wil ...

  5. Node.js能够做什么?

    正如 JavaScript 为client而生.Node.js 为网络而生.Node.js 能做的远不止开发一个网 站那么简单,使用 Node.js,你能够轻松地开发:  具有复杂逻辑的站点:  ...

  6. server问题排查经常使用命令

    1.top 查看系统负载情况,load average CPU使用情况,按1查看每一个CPU的使用情况 shift+h  查看每一个线程的情况 2.free -m   按兆为单位输出内存的已用,未用. ...

  7. LA_3135优先队列

    #include <iostream> #include <cstdio> #include <cstring> #include <queue> us ...

  8. hpuoj--校赛--2015年的第一场雪(暴力)

    问题 D: 感恩节KK专场--2015年的第一场雪 时间限制: 1 Sec  内存限制: 128 MB 提交: 865  解决: 76 [提交][状态][讨论版] 题目描述 下雪了,KK学长站在三教门 ...

  9. 机器学习规则:ML工程最佳实践----rules_of_ml section 1【翻译】

    作者:黄永刚 机器学习规则:ML工程最佳实践 本文旨在指引具有机器学习基础知识的工程师等人,更好的从机器学习的实践中收益.介绍一些应用机器学习需要遵循的规则,类似于Google C++ 风格指南等流行 ...

  10. 离奇失踪的WM_HOTKEY消息--浅析WIN32消息队列

    故事的开端有些平淡,眼红于XXX小程序,认为写完该程序就有了和心仪的妹子多相处的机会,必须搞,必须酷,按钮不能有,界面得隐藏,这就想到了全局快捷键. 注册调用RegisterHotKey(m_hWnd ...