之前有好几次碰到文件操作方面的问题,大都由于时间太赶而没有好好花时间去细致的研究研究。每次都是在百度或者博客或者论坛里面參照着大牛们写的步骤照搬过来,之后再次碰到又忘记了。刚好今天比較清闲。于是就在网上找了找Java经常使用的file文件操作方面的资料。之后加以一番整理。现分享给大家。

直接上源代码吧。

package com.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date; /**
* file operate
* @author ruanpeng
* @time 2014-11-11上午9:14:29
*/
public class OperateFileDemo { private DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
private Date start_time = null;//開始时间
private Date end_time = null;//结束时间 public static void main(String[] args) {
OperateFileDemo demo = new OperateFileDemo();
demo.operateFile1();
demo.operateFile2();
demo.operateFile3();
demo.fileCopy1();
demo.fileCopy2();
} /**
* the first method of reading file
*/
public void operateFile1(){
start_time = new Date();
File f = new File("E:"+File.separator+"test.txt");//File.separator——windows is '\'。unix is '/'
try {
//创建一个流对象
InputStream in = new FileInputStream(f);
//读取数据,并将读取的数据存储到数组中
byte[] b = new byte[(int) f.length()];//数据存储的数组
int len = 0;
int temp = 0;
while((temp = in.read()) != -1){//循环读取数据,未到达流的末尾
b[len] = (byte) temp;//将有效数据存储在数组中
len ++;
} System.out.println(new String(b, 0, len, "GBK"));
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
end_time = new Date();
System.out.println("==============第一种方式——start_time:"+df.format(start_time));
System.out.println("==============第一种方式——end_time:"+df.format(end_time));
System.out.println("==============第一种方式总耗时:"+(end_time.getTime() - start_time.getTime())+"毫秒");
}
} /**
* the second method of reading file
*/
public void operateFile2(){
start_time = new Date();
File f = new File("E:"+File.separator+"test.txt");
try {
InputStream in = new FileInputStream(f);
byte[] b = new byte[1024];
int len = 0;
while((len = in.read(b)) != -1){
System.out.println(new String(b, 0, len, "GBK"));
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
end_time = new Date();
System.out.println("==================另外一种方式——start_time:"+df.format(start_time));
System.out.println("==================另外一种方式——end_time:"+df.format(end_time));
System.out.println("==================另外一种方式总耗时:"+(end_time.getTime() - start_time.getTime())+"毫秒");
}
} /**
* the third method of reading file(文件读取(Memory mapping-内存映射方式))
* 这样的方式的效率是最好的,速度也是最快的,由于程序直接操作的是内存
*/
public void operateFile3(){
start_time = new Date();
File f = new File("E:"+File.separator+"test.txt");
try {
FileInputStream in = new FileInputStream(f);
FileChannel chan = in.getChannel();//内存与磁盘文件的通道,获取通道,通过文件通道读写文件。 MappedByteBuffer buf = chan.map(FileChannel.MapMode.READ_ONLY, 0, f.length());
byte[] b = new byte[(int) f.length()];
int len = 0;
while(buf.hasRemaining()){
b[len] = buf.get();
len++;
}
chan.close();
in.close();
System.out.println(new String(b,0,len,"GBK"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
end_time = new Date();
System.out.println("======================第三种方式——start_time:"+df.format(start_time));
System.out.println("======================第三种方式——end_time:"+df.format(end_time));
System.out.println("======================第三种方式总耗时:"+(end_time.getTime() - start_time.getTime())+"毫秒");
}
} /**
* the first method of copying file
*/
public void fileCopy1(){
start_time = new Date();
File f = new File("E:"+File.separator+"test.txt");
try {
InputStream in = new FileInputStream(f);
OutputStream out = new FileOutputStream("F:"+File.separator+"test.txt");
int len = 0;
while((len = in.read()) != -1){
out.write(len);
}
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
end_time = new Date();
System.out.println("======================第一种文件复制方式——start_time:"+df.format(start_time));
System.out.println("======================第一种文件复制方式——end_time:"+df.format(end_time));
System.out.println("======================第一种文件复制方式总耗时:"+(end_time.getTime() - start_time.getTime())+"毫秒");
}
} /**
* 使用内存映射实现文件复制操作
*/
public void fileCopy2(){
start_time = new Date();
File f = new File("E:"+File.separator+"test.txt");
try {
FileInputStream in = new FileInputStream(f);
FileOutputStream out = new FileOutputStream("F:"+File.separator+"test2.txt");
FileChannel inChan = in.getChannel();
FileChannel outChan = out.getChannel();
//开辟缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
while ((inChan.read(buf)) != -1){
//重设缓冲区
buf.flip();
//输出缓冲区
outChan.write(buf);
//清空缓冲区
buf.clear();
}
inChan.close();
outChan.close();
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
end_time = new Date();
System.out.println("======================另外一种文件复制方式——start_time:"+df.format(start_time));
System.out.println("======================另外一种文件复制方式——end_time:"+df.format(end_time));
System.out.println("======================另外一种文件复制方式总耗时:"+(end_time.getTime() - start_time.getTime())+"毫秒");
}
}
}

说明:

前面三种方法是关于文件的读取操作,第一种和另外一种是比較常见的普通方式,第三种则是採用内存映射的模式。这样的模式是直接操作内存。效率是最快的,后面两种是关于文件的读取和写入操作。

这就是上面的程序执行的结果,上面说到第三种方式是直接面向内存的,效率是最快的,但是我们发现第三种的执行结果却还没有另外一种方式快,详细的原因我还没有进行深入探究,并且我的文件容量也比較小,看不出什么本质的效果,并且这个也不过读取操作,但最后的那个文件复制操作效果就相当明显了。不不过读取操作。同一时候还涉及到了文件的写操作,普通的复制方式须要105毫秒。而採用内存映射的方式只只须要1毫秒。效果立刻明晓了。

至于读操作的效率问题有兴趣的朋友能够去深入探究一番。

原文出处:http://www.open-open.com/lib/view/open1415448427183.html

java中的File文件读写操作的更多相关文章

  1. Java 字符流实现文件读写操作(FileReader-FileWriter)

    Java 字符流实现文件读写操作(FileReader-FileWriter) 备注:字符流效率高,但是没有字节流底层 字节流地址:http://pengyan5945.iteye.com/blog/ ...

  2. java学习(九) —— java中的File文件操作及IO流概述

    前言 流是干什么的:为了永久性的保存数据. IO流用来处理设备之间的数据传输(上传和下载文件) java对数据的操作是通过流的方式. java用于操作流的对象都在IO包中. java IO系统的学习, ...

  3. java中实现File文件的重命名(renameTo)、将文件移动到其他目录下、文件的复制(copy)、目录和文件的组合(更加灵活方便)

    欢迎加入刚建立的社区:http://t.csdn.cn/Q52km 加入社区的好处: 1.专栏更加明确.便于学习 2.覆盖的知识点更多.便于发散学习 3.大家共同学习进步 3.不定时的发现金红包(不多 ...

  4. JAVA基于缓冲的文件读写操作

    File f2 = new File("e://index.java"); BufferedReader reader = new BufferedReader(new Input ...

  5. java文件读写操作类

    借鉴了项目以前的文件写入功能,实现了对文件读写操作的封装 仅仅需要在读写方法传入路径即可(可以是绝对或相对路径) 以后使用时,可以在此基础上改进,比如: 写操作: 1,对java GUI中文本框中的内 ...

  6. Java 字节流实现文件读写操作(InputStream-OutputStream)

    Java 字节流实现文件读写操作(InputStream-OutputStream) 备注:字节流比字符流底层,但是效率底下. 字符流地址:http://pengyan5945.iteye.com/b ...

  7. [转]Android - 文件读写操作 总结

     转自:http://blog.csdn.net/ztp800201/article/details/7322110 Android - 文件读写操作 总结 分类: Android2012-03-05 ...

  8. Kotlin入门(27)文件读写操作

    Java的文件处理用到了io库java.io,该库虽然功能强大,但是与文件内容的交互还得通过输入输出流中转,致使文件读写操作颇为繁琐.因此,开发者通常得自己重新封装一个文件存取的工具类,以便在日常开发 ...

  9. Kotlin入门-文件读写操作

    转 https://blog.csdn.net/aqi00/article/details/83241762 Java的文件处理用到了io库java.io,该库虽然功能强大,但是与文件内容的交互还得通 ...

随机推荐

  1. 刷题总结——ball(ssoj)

    题目: 题目背景 SOURCE:NOIP2015-SHY-9 题目描述 Alice 与 Bob 在玩游戏.他们一共玩了 t 轮游戏.游戏中,他们分别获得了 n 个和 m 个小球.每个球上有一个分数.每 ...

  2. docker 镜像阿里加速器

    1.登录 https://cr.console.aliyun.com/#/imageList 2.点击加速器tab,获取自己的加速器地址,然后执行黑框内的命令. .sudo mkdir -p /etc ...

  3. vue 配合 element-ui使用搭建环境时候遇到的坑

    在需要使用element-ui的时候,直接引入文件,发现会报错,解析不了css文件和字体,需要在webpack里面配置上css-loader和style-loader,最好的做法是把element-u ...

  4. spoj 7001 Visible Lattice Points莫比乌斯反演

    Visible Lattice Points Time Limit:7000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu Su ...

  5. windows8.1如何分盘

    磁盘分区首先要弄明白磁盘物理顺序与逻辑顺序的区别,在[磁盘管理]界面,所显示的前后顺序为物理顺序,这是磁盘上实实在在的物理位置,如下图2的电脑磁盘物理顺序为CFDE.在[资源管理器]界面,所显示的顺序 ...

  6. Day 17 编码+文本编辑+函数

    知识点篇: #! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "DaChao" # Date: 2017/ ...

  7. Javascript 评估用户输入密码的强度

    什么是一个安全的密码呢? 1.如果密码少于5位,那么就认为这是一个弱密码. 2.如果密码只由数字.小写字母.大写字母或其它特殊符号当中的一种组成,则认为这是一个弱密码. 3.如果密码由数字.小写字母. ...

  8. (2)Unity3d菜单

    1.文件菜单 2.编辑菜单 Frame Selected 焦点选择和双击Hierarchy中的元素一样的功能 Lock View to Selected  选中对象再点击此按钮,在场景视图中移动此对象 ...

  9. jvm类加载的过程

    java类加载过程:加载-->验证-->准备-->解析-->初始化,之后类就可以被使用了.绝大部分情况下是按这 样的顺序来完成类的加载全过程的.但是是有例外的地方,解析也是可以 ...

  10. 华硕win7安装ubuntu14.04.02注意事项

    一.win7下划出给ubuntu系统的分区 1.win7自带分磁盘的工具,只需要压缩步骤即可,不需要继续分盘符格式化等操作 win7下为绿色 安装时为free space 二.制作启动盘并安装注意事项 ...