java中的File文件读写操作

之前有好几次碰到文件操作方面的问题,大都因为时间太赶而没有好好花时间去仔细的研究研究,每次都是在百度或者博客或者论坛里面参照着大牛们写的步骤照搬过来,之后再次碰到又忘记了,刚好今天比较清闲,于是就在网上找了找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

时间: 2024-08-27 05:43:46

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

java文件读写操作类

借鉴了项目以前的文件写入功能,实现了对文件读写操作的封装 仅仅需要在读写方法传入路径即可(可以是绝对或相对路径) 以后使用时,可以在此基础上改进,比如: 写操作: 1,对java GUI中文本框中的内容进行捕获,放在txt文本文档中 2,对各种类型数据都以字符串的形式逐行写入 3,对全局数组的内容进行写入 读操作: 获取文件行数 对逐行字符串型数据进行类型转换,放入二维数组中 为后面算法处理提供入口,但是要小心的是:不可以将行数用全局变量做计数器,否则每次读入是全局变量累加出错,应重新开始读取

Android数据存储——文件读写操作(File)

Android文件读写操作 一.文件的基本操作 Android中可以在设备本身的存储设备或外接的存储设备中创建用于保存数据的文件.在默认状态下,文件是不能在不同程序间共享的. 当用户卸载您的应用程序时,这些文件删除. 文件存储数据可以通过openFileOutput方法打开一个文件(如果这个)文件不存在就自动创建这个文件),通过load方法来获取文件中的 数据,通过deleteFile方法删除一个指定的文件. 1,常用方法介绍: File是通过FileInputStream和FileOutput

【python学习笔记】pthon3.x中的文件读写操作

在学习python文件读写的时候,因为教程是针对python2的,而使用的是python3.想要利用file类时,类库里找不到,重装了python2还是使不了.在别人园子认真拜读了<详解python2和python3区别>(已收藏)之后,才发现python3已经去掉file类. 现在利用python进行文件读写的方法更加类似于C语言的文件读写操作. 如今总结如下: 一 打开文件—— f = open('poem.txt','x+'): 读过open的帮助文档,然后自己翻译了一下,现给大家分享一

java file文件类操作使用方法大全

1.构造函数 [java] view plaincopy public class FileDemo { public static void main(String[] args){ //构造函数File(String pathname) File f1 =new File("c:\\zuidaima\\1.txt"); //File(String parent,String child) File f2 =new File("c:\\zuidaima",&quo

java中IO写文件工具类

下面是一些根据常用java类进行组装的对文件进行操作的类,平时,我更喜欢使用Jodd.io中提供的一些对文件的操作类,里面的方法写的简单易懂. 其中jodd中提供的JavaUtil类中提供的方法足够我们使用,里面的方法写的非常简练,例如append,read等方法,封装更好,更符合面向对象, 这里面我写的一些方法可多都是模仿jodd,从里面进行抽取出来的. /** * 获取路径文件夹下的所有文件 * @param path * @return */ public static File[] ge

php学习基础-文件系统(二) 文件读写操作、文件资源处理

一.文件的打开与关闭 /* *读取文件中的内容 * file_get_contents(); //php5以上 * file() * readfile(); * * 不足:全部读取, 不能读取部分,也不能指定的区域 * * fopen() * fread() * fgetc() * fgets() * * * * * 写入文件 * file_put_contents("URL", "内容字符串"); //php5以上 * 如果文件不存在,则创建,并写入内容 * 如果

java中的File类

File类 java中的File类其实和文件并没有多大关系,它更像一个对文件路径描述的类.它即可以代表某个路径下的特定文件,也可以用来表示该路径的下的所有文件,所以我们不要被它的表象所迷惑.对文件的真正操作,还得需要I/O流的实现. 1.目录列表 如果我们想查看某个目录下有那些文件和目录,我们可以使用File中提供的list方式来查看,这很像linux下的ls命令. 查看E:/html文件夹下所有的php文件,执行的时候输入的参数为正则表达式 1 package com.dy.xidian; 2

C语言文件读写操作,从文件读取数据

很早写的在linux系统下的文件读写操作,从文件中读取数据 #include <stdio.h> int ReadInfoFromFile(const char *strFile) { FILE *fp; char ch; fp = fopen(strFile, "r"); // 只读的方式打开文件 if(fp==NULL) { perror("fopen"); // 打开文件失败 打印错误信息 return -1; } ch = fgetc(fp);

Android中使用File文件进行数据存储

Android中使用File文件进行数据存储 上一篇学到使用SharedPerences进行数据存储,接下来学习一下使用File进行存储 我们有时候可以将数据直接以文件的形式保存在设备中, 例如:文本文件,图片文件等等 使用File进行存储操作主要使用到以下的 ①:public abstract FileInputStream openFileInput (String name) 这个主要是打开文件,返回FileInputStream ②:public abstract FileOutputS