当前位置: 代码迷 >> Java相关 >> io流大数据边读边批改 内存溢出
  详细解决方案

io流大数据边读边批改 内存溢出

热度:21   发布时间:2016-04-22 20:51:11.0
io流大数据边读边修改 内存溢出

public void ipTest(File newFileName){


String[] str1;
String str = "";
BufferedReader in=null;
BufferedWriter out=null;
try {
 in = new BufferedReader(
new InputStreamReader(
  new BufferedInputStream(
new FileInputStream(excel)),"GBK"));
 out=new BufferedWriter(
new OutputStreamWriter(
  new BufferedOutputStream(
new FileOutputStream(newFileName)),"GBK"));
int fistHead=1;
while ((str = in.readLine()) != null) {
str1 = str.split(",");
if(fistHead==1){
out.write(str +",省市");
out.newLine();
// bw.append(str +",省市");
fistHead+=1;
continue;
}
out.write(str +","+ IpUtils.getCityAddress(str1[1]));
out.newLine();
//bw.append(str +","+ IpUtils.getCityAddress(str1[1]));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(in != null){in.close();}
if(out != null){out.close();}
} catch (IOException e) {
e.printStackTrace();
}

}

}


按行读取 怎么在原代码的基础上 怎么控制?  数据量大概是70W的时候 内存就会溢出  CSV文件读取的 


------解决思路----------------------
最简单的方法是不要用该死的BufferedReader和BufferedInputStream
翻了下BufferedInputStream的源码,似乎也可以用BufferedInputStream.mark(int readlimit)方法来让BufferedInputStream抛弃已经读过的内容
------解决思路----------------------
对于BufferedOutputStream,则是定期使用flush()来清空缓存。当然了,不用BufferedOutputStream更好……
------解决思路----------------------
对于大文件操作,可以使用NIO中的内存映射文件
//读取文件
FileChannel fcIn = new RandomAccessFile("", "r").getChannel();
MappedByteBuffer map = fcIn.map(FileChannel.MapMode, start,length );

//写出文件
FileChannel fcOut = new RandomAccessFile("", "rw").getChannel();
MappedByteBuffer map = fcOut.map(FileChannel.MapMode, start,length );
具体方法网上自己查查吧。
------解决思路----------------------
按行读取 怎么在原代码的基础上 怎么控制? 

处理玩一定数量的行数时,out.flush();试试。
  相关解决方案