刚才使用如下代码进行测试,得到了如下下的结果!!
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Created by yangjunlin on 8/14/15.
*/
public class FileTest
{
public static void main(String[] dd)
{
Path path = Paths.get("/home/yangjunlin/Downloads/ubuntu-14.04.2-desktop-amd64.iso");
System.out.println(path.getFileName());
long begin1 = System.nanoTime();
try (RandomAccessFile randomAccessFile = new RandomAccessFile(path.toFile(), "rw"))
{
System.out.println("RandomAccessFile length: " + randomAccessFile.length());
System.out.println("RandomAccessFile nanoTime: " + (System.nanoTime() - begin1));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
long begin2 = System.nanoTime();
System.out.println("File length: " + path.toFile().length());
System.out.println("File nanoTime: " + (System.nanoTime() - begin2));
long begin3 = System.nanoTime();
try (FileInputStream fileInputStream = new FileInputStream(path.toFile()))
{
System.out.println("FileInputStream length: " + fileInputStream.available());
System.out.println("FileInputStream nanoTime: " + (System.nanoTime() - begin3));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
long begin4 = System.nanoTime();
try (FileChannel fileChannel = new FileInputStream(path.toFile()).getChannel())
{
System.out.println("FileChannel length: " + fileChannel.size());
System.out.println("FileChannel nanoTime: " + (System.nanoTime() - begin4));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
结果如下:
ubuntu-14.04.2-desktop-amd64.iso
RandomAccessFile length: 1044381696
RandomAccessFile nanoTime: 449054
File length: 1044381696
File nanoTime: 80385
FileInputStream length: 1044381696
FileInputStream nanoTime: 108946
FileChannel length: 1044381696
FileChannel nanoTime: 3220354
装饰越多越慢呀。
在读超大文件的时候会有坑,见这里:http://blog.csdn.net/chaijunkun/article/details/22387305