字符串大概有1~2mb,每次读取都要1s多,如何进行优化?根据以下方法,为什么nio比io还慢?哪里写的有问题?//普通IO耗时1.3s public static String openStringFileIO(String path, String fileName) { long time = System.currentTimeMillis(); String result = null; File f = new File(path, fileName); try { FileInputStream fileInputStream = new FileInputStream(f); StringBuilder buffer = new StringBuilder(); String line; BufferedReader in = new BufferedReader(new InputStreamReader(fileInputStream)); while ((line = in.readLine()) != null) { buffer.append(line); } result = buffer.toString(); } catch (IOException e) { e.printStackTrace(); } Logger.d("openStringFileIO " + (System.currentTimeMillis() - time)); return result; } //NIO耗时 2.5s public static String openStringFileNIO(String path, String fileName) { long time = System.currentTimeMillis(); FileInputStream in = null; StringBuilder result = new StringBuilder(); try { File f = new File(path, fileName); in = new FileInputStream(f); FileChannel fc = in.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); // 定义字节缓冲区 CharBuffer charBuffer = CharBuffer.allocate(1024); // 定义解码后字符存储缓冲区 CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();// 定义合适的字符集解码器 while ((fc.read(byteBuffer)) != -1) { // 读取字符串到缓冲区 byteBuffer.flip(); charBuffer.clear(); // 对byteBuffer进行解码 if (fc.position() < fc.size()) { decoder.decode(byteBuffer, charBuffer, false); } else { // 最后一次解码 decoder.decode(byteBuffer, charBuffer, true); decoder.flush(charBuffer); } byteBuffer.compact(); // 注意此处调用compact方法,而不是clear方法 charBuffer.flip();
添加回答
举报
0/150
提交
取消