在我们写的java程序中,一般都会遇到很多读取和写入大的文件的情况,我们通常利用java.io里面的Bufferreadered类等等去读取或则写入文件,接下来我介绍一些读取大文件的快速的方法。
读取文件的方法:
1.利用java.nio.file
这个主要是利用的以下的类和方法:
import java.nio.file.Files;
import java.nio.file.Paths;
利用Files.readAllBytes(Paths.get(filePath))获取filePath路径里面的文件的所有的内容,这个方法返回的是一个字节数组,然后,就可以调用new String()方法创建一个字符串了。代码如下:
public String input(String filePath) {
String p=new String();
try {
p = new String(Files.readAllBytes(Paths.get(filePath)));
} catch (IOException e) {
e.printStackTrace();
}
return p;
}
这样的话就可以返回文件的所有内容到一个字符串了。如果想要将他们分隔开为一行一行的,可以进行如下处理:
String[] ss = s.split("\n|\r");
这样就可以对ss数组里面的字符串进行各种操作了。
2.利用FileInputStream
这种方法主要是使用了以下类:
import java.io.File;
import java.io.FileInputStream;
这个方法是利用字节流来读取文件的内容,需要首先开一个字节数组,当文件比较大的时候,我们盲目的开的话会造成内存的空间损失。带来不必要的麻烦。我们可以申请读取进来的文件内容大小的字节数组。然后利用FileInputStream读入流获取字节,再利用new String(bytes, offset, length)构建出字符串对象即可,代码如下:
public String input(String filePath) {
File file = new File(filePath);
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
String p = new String();
try {
FileInputStream in = new FileInputStream(file);
p=new String(filecontent,0,in.read(filecontent));
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return p;
}
3.利用java.nio.ByteBuffer
这个方法首先利用new RandomAccessFile(file, "r").getChannel().map获取一个ByteBuffer的对象,同时,创建一个CharBuffer对象,然后把ByteBuffer类型的对象转换成CharBuffer类型的对象。然后调用CharBuffer类型的toString()方法获取字符串。代码如下:
public String input(String filePath) {
String p = new String();
File file = new File(filePath);
CharBuffer charBuffer = null;
try {
ByteBuffer mbb = new RandomAccessFile(file, "r").getChannel()
.map(FileChannel.MapMode.READ_ONLY, 0,
file.length());
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
charBuffer = decoder.decode(mbb);
mbb.flip();
p = charBuffer.toString();
} catch (IOException e) {
e.printStackTrace();
}
return p;
}
读取一个大约30MB的文件的时间:
FileInputStream:
File.readAllBytes:
ByteBuffer:
由此可以看出它们读取的时间都是很快的,比较而言FileInputStream和File.readAllBytes更快一些。
写回文件:
1.利用java.io.FileWriter
直接利用FileWriter的write方法,将相应的字符串写回到路径当中:
public void output(String filename,String str) {
FileWriter fw;
try {
fw = new FileWriter(filename);
fw.write(str, 0, str.length());
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2.利用FileOutputStream
使用FileOutputStream类的write写回方法,如下:
public void output(String filename, String str) {
FileOutputStream fos;
try {
fos = new FileOutputStream(filename);
fos.write(str.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
3.利用BufferedOutputStream
使用BufferedOutputStream类的write协会方法,如下:
public void output(String filename, String str) {
BufferedOutputStream buff;
try {
buff = new BufferedOutputStream(new FileOutputStream(filename));
buff.write(str.getBytes());
buff.flush();
buff.close();
} catch (IOException e) {
e.printStackTrace();
}
}
写回上述的一个30MB大小的文件的时间:
FileWriter:
FileOutputStream:
BufferedoutputStream:
相比较而言,FileOutputStream的性能比其他两个要慢很多,所以推荐使用其他两个更快。