62,614
社区成员
发帖
与我相关
我的任务
分享
FileUtil.createFile("D:\\fileTest\\test.txt");
RandomAccessFile aFile = new RandomAccessFile("D:\\fileTest\\test.txt", "rw");
FileChannel channel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(2048);
StringBuffer sub = null;
long l = System.currentTimeMillis();
for (int i = 0; i < 200000; i++) {
sub = new StringBuffer();
for (int j = 0; j < 60; j++) {
sub.append("“很好,有些见地。”");
if (j < 39) {
sub.append(",");
}
}
buffer.put(sub.toString().getBytes());
buffer.put("\r\n".getBytes());
buffer.flip();
channel.write(buffer);
buffer.clear();
}
channel.close();
aFile.close();
System.out.println("执行时间:" + (System.currentTimeMillis() - l));
---------------------------------------------------------------
1.执行时间:3667
2.执行时间:3320
3.执行时间:3353
三观被颠覆了,能不能解释一下。
public static void main(String[] args) throws IOException {
long l = System.currentTimeMillis();
BufferedReader br = null;
String sCurrentLine = null;
try {
br = new BufferedReader(new FileReader("test.txt"));
while ((sCurrentLine = br.readLine()) != null) {
// System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println("IO执行时间:" + (System.currentTimeMillis() - l));
l = System.currentTimeMillis();
RandomAccessFile aFile = new RandomAccessFile("test.txt", "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (inChannel.read(buffer) > 0) {
buffer.flip();
for (int i = 0; i < buffer.limit(); i++) {
// System.out.print((char) buffer.get());
}
buffer.clear(); // do something with the data and clear/compact it.
}
inChannel.close();
aFile.close();
System.out.println("NIO执行时间:" + (System.currentTimeMillis() - l));
}