我试图弄清楚当我们使用nio FileChannel与普通FileInputStream/FileOuputStream文件读取和写入文件系统时,性能(或优势)是否有任何差异.我观察到,在我的机器上,两者都在同一级别执行,也很多次FileChannel都是慢一些.我可以了解比较这两种方法的更多细节.这是我使用的代码,我正在测试的文件是350MB.如果我不是在查看随机访问或其他此类高级功能,那么对文件I/O使用基于NIO的类是一个不错的选择吗?
package trialjavaprograms;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class JavaNIOTest {
public static void main(String[] args) throws Exception {
useNormalIO();
useFileChannel();
}
private static void useNormalIO() throws Exception {
File file = new File("/home/developer/test.iso");
File oFile = new File("/home/developer/test2");
long time1 = System.currentTimeMillis();
InputStream is = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(oFile);
byte[] buf = new byte[64 * 1024];
int len = 0; …Run Code Online (Sandbox Code Playgroud) 有没有理由在下面选择a CharBuffer到a char[]:
CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
while( in.read(buf) >= 0 ) {
out.append( buf.flip() );
buf.clear();
}
Run Code Online (Sandbox Code Playgroud)
与
char[] buf = new char[DEFAULT_BUFFER_SIZE];
int n;
while( (n = in.read(buf)) >= 0 ) {
out.write( buf, 0, n );
}
Run Code Online (Sandbox Code Playgroud)
(ina Reader和outa 在哪里Writer)?