java常用的文件读写操作

现在算算已经做java开发两年了,回过头想想还真是挺不容易的,java的东西是比较复杂但是如果基础功扎实的话能力的提升就很快,这次特别整理了点有关文件操作的常用代码和大家分享

1.文件的读取(普通方式)

(1)第一种方法

File f=new File("d:"+File.separator+"test.txt");
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();

这种方法貌似用的比较多一点

(2)第二种方法

File f=new File("d:"+File.separator+"test.txt");
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();

2.文件读取(内存映射方式)

File f=new File("d:"+File.separator+"test.txt");
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"));

这种方式的效率是最好的,速度也是最快的,因为程序直接操作的是内存


3.文件复制(边读边写)操作

(1)比较常用的方式

package org.lxh;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class ReadAndWrite {

	public static void main(String[] args) throws Exception {
		File f=new File("d:"+File.separator+"test.txt");
        InputStream in=new FileInputStream(f);
        OutputStream out=new FileOutputStream("e:"+File.separator+"test.txt");
        int temp=0;
        while((temp=in.read())!=-1){
        	out.write(temp);
        }
        out.close();
        in.close();
	}

}

(2)使用内存映射的实现

package org.lxh;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadAndWrite2 {

   public static void main(String[] args) throws Exception {
	File f=new File("d:"+File.separator+"test.txt");
	FileInputStream in=new FileInputStream(f);
	FileOutputStream out=new FileOutputStream("e:"+File.separator+"test.txt");
        FileChannel fin=in.getChannel();
        FileChannel fout=out.getChannel();
        //开辟缓冲
        ByteBuffer buf=ByteBuffer.allocate(1024);
        while((fin.read(buf))!=-1){
        	//重设缓冲区
        	buf.flip();
        	//输出缓冲区
        	fout.write(buf);
        	//清空缓冲区
        	buf.clear();
        }
        fin.close();
        fout.close();
        in.close();
        out.close();
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值