您的位置:首页 > 编程语言 > Java开发

java常用的文件读写操作

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

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

(1)第一种方法

[java] view plain copy







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)第二种方法

[java] view plain copy







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.文件读取(内存映射方式)

[java] view plain copy







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)比较常用的方式

[java] view plain copy







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)使用内存映射的实现

[java] view plain copy







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();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: