java中怎么实现高效文件流读写操作?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
文件流比较
下面重点比较我们经常用的几个流
(1) DataInputStream+FileInputStream
(2) DataInputStream+BufferedInputStream
(3) BufferedReader+FileReader(缓冲流大小不同性能也不同,如1K和8K)
(4) BufferedFileReader
先贴结论:
耗时对比为:
(4)优于(3)—8096优于(3)-1024优于(2)<(1)
另外,BufferedFileReader如果涉及到读取文件的每一行内容还可以在优化,传统的代码如下所示:
BufferedFileReader in = new BufferedFileReader();
for (int i=0; i < nargs; i++) {
try {
in.open(args[i]);
while ((line = in.readLine()) != null) {
nlines++;
} in.close();
} catch (Exception e) {
System.out.println(" BFRTest: exception:" + e );
}
代码中第5行,BufferedReader首先生成一个StringBuffer,然后转成一个String返回,这里涉及到两次字符拷贝。假设读取10000行,会有10000个临时的String对象生成,内存比较耗费,由于BufferedReader的缓冲流是私有的,因此这里的优化点是可以自己管理缓冲流。最佳的读文件的方法代码如下:
FileReader fr;
int nlines = 0;
char buffer[] = new char[8192 + 1];
int maxLineLength = 128;
//assumes no line is longer than this
char lineBuf[] = new char[maxLineLength];
for (int i = 0; i < nargs; i++) {
try {
fr = new FileReader(args[i]);
int nChars = 0;
int nextChar = 0;
int startChar = 0;
boolean eol = false;
int lineLength = 0;
char c = 0;
int n;
int j;
while (true) {
if (nextChar >= nChars) {
n = fr.read(buffer, 0, 8192);
if (n == -1) { // EOF
break;
}
nChars = n;
startChar = 0;
nextChar = 0;
}
for (j = nextChar; j < nChars; j++) {
c = buffer[j];
if ((c == '\n') || (c == '\r')) {
eol = true;
break;
}
}
nextChar = j;
int len = nextChar - startChar;
if (eol) {
nextChar++;
if ((lineLength + len) > maxLineLength) {
// error
} else {
System.arraycopy(buffer, startChar, lineBuf, lineLength, len);
}
lineLength += len;
//
// Process line here
//
nlines++;
if (c == '\r') {
if (nextChar >= nChars) {
n = fr.read(buffer, 0, 8192);
if (n != -1) {
nextChar = 0;
nChars = n;
}
}
if ((nextChar < nChars) && (buffer[nextChar] == '\n'))
nextChar++;
}
startChar = nextChar;
lineLength = 0;
continue;
}
if ((lineLength + len) > maxLineLength) {
// error
} else {
System.arraycopy(buffer, startChar, lineBuf, lineLength, len);
}
lineLength += len;
}
fr.close();
} catch (Exception e) {
System.out.println("exception: " + e);
}
看完上述内容,你们掌握java中怎么实现高效文件流读写操作的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。