读书人

java io 的有关问题

发布时间: 2012-03-14 12:01:13 作者: rapoo

java io 的问题!
请教各位大侠,java io 操作从文件读取数据那一(几)个类效率较高?
在线等>>>
谢谢!

[解决办法]

java.io.FileInputStream


[解决办法]
java.io.BufferedReader
[解决办法]
BufferedInputStream 应该效率高些。 最基本的道理,减少disk access的次数嘛。
[解决办法]
用nio, 效率高:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;



/** *//**
* @author maoyeye
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class FileUtil ...{

public static ByteBuffer readFile(String filename) throws Exception
{
FileChannel fiChannel = new FileInputStream(filename).getChannel();
MappedByteBuffer mBuf;
mBuf = fiChannel.map(FileChannel.MapMode.READ_ONLY, 0, fiChannel.size());
fiChannel.close();
fiChannel = null;

return mBuf;

}


public static void saveFile(ByteBuffer src, String filename) throws Exception
{
FileChannel foChannel = new FileOutputStream(filename).getChannel();
foChannel.write(src);
foChannel.close();
foChannel = null;
}

public static void saveFile(FileChannel fiChannel, String filename) throws IOException
{
MappedByteBuffer mBuf;
mBuf = fiChannel.map(FileChannel.MapMode.READ_ONLY, 0, fiChannel.size());

FileChannel foChannel = new FileOutputStream(filename).getChannel();
foChannel.write(mBuf);

fiChannel.close();
foChannel.close();

fiChannel = null;
foChannel = null;
}


public static void main(String[] args) throws Exception
{
final String suffix = ".txt";
final String filename = "bufferTemp";
final String srcFile = filename + suffix ;
final String backupFile = filename + "-" + System.currentTimeMillis() + suffix;
ByteBuffer byteBuffer = FileUtil.readFile(srcFile);
FileUtil.saveFile(byteBuffer, backupFile);
byteBuffer = null;

}
}
[解决办法]
一般用Buffered*的类效率要高些。
[解决办法]
一般用Buffered*的类效率要高些。

同意

读书人网 >J2SE开发

热点推荐