转:Java读写文件各种方法及性能比较
干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读写文件各种方法及性能比较的更多相关文章
- Java读写文件方法总结
Java读写文件方法总结 Java的读写文件方法在工作中相信有很多的用处的,本人在之前包括现在都在使用Java的读写文件方法来处理数据方面的输入输出,确实很方便.奈何我的记性实在是叫人着急,很多时候既 ...
- java读写文件大全
java读写文件大全 最初java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类,这两个类都是抽象类,Writer中 write(char[] ch,int o ...
- C#读写文件的方法汇总_C#教程_脚本之家
C#读写文件的方法汇总_C#教程_脚本之家 http://www.jb51.net/article/34936.htm
- Java读写文件的几种方式
自工作以后好久没有整理Java的基础知识了.趁有时间,整理一下Java文件操作的几种方式.无论哪种编程语言,文件读写操作时避免不了的一件事情,Java也不例外.Java读写文件一般是通过字节.字符和行 ...
- 【java】java 读写文件
场景:JDK8 将上传的文件,保存到服务器 Java读写文件操作: MultipartFile file InputStream inputStream = file.getInputStream( ...
- 【转】Java读写文件大全
使用Java操作文本文件的方法详解 最初java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类,这两个类都是抽象类,Writer中 write(ch ...
- java 读写文件常用方法
package study.bigdata; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; ...
- java读写文件IO
package Common.readFile; import Common.tool.User; import com.fasterxml.jackson.databind.ObjectMapper ...
- Java读写文件常用方法
一.字符流:读写纯文本(txt,csv等), 1 字符流写文件主要用:FileWriter,BufferedWriter,PrintWriter 1.1 测试 FileWriter 写入 privat ...
随机推荐
- mayan 游戏 search
纯搜索,,,模拟,,还不算太难,,就是细节略繁琐 首先因为题目要求保证字典序,所以显然把右边的块换到左边不如把左边的块换到右边优, 所以可以进行不小规模的剪枝,之后显然交换两块相同的色块没有意义,至此 ...
- C - The C Answer (2nd Edition) - Exercise 1-12
/* Write a program that prints its input one word per line. */ #include <stdio.h> #define IN 1 ...
- java线程共享受限资源 解决资源竞争 thinking in java4 21.3
java线程共享受限资源 解决资源竞争 具体介绍请參阅:thinking in java4 21.3 thinking in java 4免费下载:http://download.csdn.net/ ...
- C#重构经典全面汇总
C#重构经典全面汇总 1. 封装集合 概念:本文所讲的封装集合就是把集合进行封装,仅仅提供调用端须要的接口. 正文:在非常多时候,我们都不希望把一些不必要的操作暴露给调用端,仅仅须要给它所须要的操作 ...
- git的学习笔记整理
Git学习较好的网址:http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000/001373 ...
- ELK搭建(filebeat、elasticsearch、logstash、kibana)
ELK部署(文章有点儿长,搭建时请到官网将tar包下载好,按步骤可以完成搭建使用) ELK指的是ElasticSearch.LogStash.Kibana三个开源工具 LogStash是负责数据的收集 ...
- Hadoop-CDH源码编译
* Hadoop-CDH源码编译 这一节我们主要讲解一下根据CDH源码包手动编译的过程,至于为什么要使用CDH,前几节已经说明,那为什么又要自己手动编译,因为CDH的5.3.6对应的Hadoop2.5 ...
- ViewPager设置不能滚动
设置ViewPager不能滑动 1:设置当前选中的页面 public void setCurrentItem(int item) { mPopulatePending = false; setCurr ...
- c# IndexOf()用法
IndexOf()用法 查找字符串中字符或者字符串首次出现的位置,返回的是索引值; str1.indexOf('字');//查找“字”在字符串中首次出现的索引值 str1.indexOf(" ...
- monitoring_db
#!/bin/bash# Program: # Automatic inspection operation system and oracle database.# History:# 2016/0 ...