日期:2014-05-20 浏览次数:20994 次
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
/**
* @ 测试结论:只要缓冲大小设置得当,使用旧io和基本类型写的IO是最快的。
* @author jdgdf566
*/
public class NewMain {
private static int commonIObuffer = 1024 * 32;
/**
* nio内存映射
*
* @throws IOException
*/
public static void mapChannel() throws IOException {
FileInputStream in = new FileInputStream("Java NIO (JSR 51 NIO.1)中文版.pdf");
long size = in.available();
RandomAccessFile out = new RandomAccessFile(Double.toString(Math.random()), "rw");
FileChannel inc = in.getChannel();
MappedByteBuffer bf = inc.map(FileChannel.MapMode.READ_ONLY, 0, size);
FileChannel outc = out.getChannel();
MappedByteBuffer outbf = outc.map(FileChannel.MapMode.READ_WRITE, 0, size);
outbf.put(bf);
inc.close();
outc.close();
in.close();
out.close();
}
/**
* 原io
*
* @throws IOException
*/
public static void commonIO() throws Exception {
NewMain.fileToStream("Java NIO (JSR 51 NIO.1)中文版.pdf", new FileOutputStream(Double.toString(Math.random())));
}
public static int fileToStream(String path, OutputStream out) throws Exception {
int bufferSize = commonIObuffer;
FileInputStream fis = new FileInputStream(path);
//ba文件写入liu
int dataSize = 0;
int len;
byte[] bs = new byte[bufferSize];
while ((len = fis.read(bs)) != -1) {
out.write(bs, 0, len);
dataSize += len;
}
out.flush();
return dataSize;
}
/**
* nio
*
* @throws IOException
*/
public static void channel_transferTo() throws Exception {
String path = "F:\\NetBeansProjects\\JavaApplicationTest\\src\\Java NIO (JSR 51 NIO.1)中文版.pdf";
//String outpath = "F:\\NetBeansProjects\\JavaApplicationTest\\src/0.2974592999005251";
FileChannel fileChannel = FileChannel.open(Paths.get(path));
fileChannel.transferTo(0, fileChannel.size(), Channels.newChannel(new BufferedOutputStream(new FileOutputStream(Double.toString(Math.random())), commonIObuffer)));
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
long t1 = System.currentTimeMillis();
//NewMain.mapChannel();