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*的类效率要高些。
同意