package read_write;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Writer;
/**
* 主要解决大文本文件的迁移过大造成的内存溢出问题,采用边读边写
* @author zhao
*
*/
public class Demo {
public static void main(String[] args) {
read_write("src/read_write/ChannelScanQuery.xml","src/read_write/ChannelScanQuery_write.xml");
}
/**
* 从一个文件每读取百行向第二个参数指定的目录下文件中写入一次;
* 如果第二个参数指定的目录下文件已经存在,则覆盖原文件;
* @param filename
* @param filename
* @author zhao
*/
public static void read_write(String filename,String desXMLPath){
//文件大小
long epgSize=0;
try {
RandomAccessFile br=new RandomAccessFile(filename,"rw");//这里rw看你了。要是只读就只写r
String str = null;
//读取的行数标记、每轮读取100行
int i=0;
//读取的轮数标记
int num=0;
//每轮读取到的文本
String EPGXMLStr="";
while ((str = br.readLine()) != null) {
str = new String(str.getBytes("ISO-8859-1"),"gb2312");
i++;
EPGXMLStr=EPGXMLStr+str+"\n";
if(i>=100){//先定每轮读取100行
i=0;
num++;
System.out.println("读取到的EPG文件行数(单位:百行)"+num);
//首轮读取,保存在一个新创建的文件中
if(num==1){
WriteFile_new(EPGXMLStr,desXMLPath);
}else{
WriteFile(EPGXMLStr,desXMLPath);
}
epgSize=epgSize+EPGXMLStr.length();
EPGXMLStr="";
}
}
if(i>0){
epgSize=epgSize+EPGXMLStr.length();
if(num==0){
WriteFile_new(EPGXMLStr,desXMLPath);
}else{
WriteFile(EPGXMLStr,desXMLPath);
}
EPGXMLStr="";
}
br.close();
} catch (Exception e) {
System.out.println("读取到的EPG文件出错"+e.getMessage());
// TODO: handle exception
}
System.out.println("文件大小:"+epgSize);
}
/**
* 创建一个文件并向其写入一段文本
* 写文件时转码为GB2312
* @param StoreStr 文本
* @param filename 地址
* @param filename
* @author zzb
*/
public static void WriteFile_new(String StoreStr, String filename) {
try {
if(StoreStr == null || StoreStr.equals("")) {
return;
}
FileOutputStream os = new FileOutputStream(filename,false);
Writer out = new OutputStreamWriter(os, "GB2312");
out.write(StoreStr);
out.close();
os.close();
//log.info("文件保存成功");
} catch (IOException ioe) {
System.out.println("WriteFile, IOException: " + ioe
.getMessage());
}
}
/**
* 写文件时转码为GB2312
* @param StoreStr
* @param filename
* @author zzb
*/
public static void WriteFile(String StoreStr, String filename) {
try {
if(StoreStr == null || StoreStr.equals("")) {
return;
}
//log.info("文件保存到:" + filename);
FileOutputStream os = new FileOutputStream(filename,true);
Writer out = new OutputStreamWriter(os, "GB2312");
out.write(StoreStr);
out.close();
os.close();
//log.info("文件保存成功");
} catch (IOException ioe) {
System.out.println("WriteFile, IOException: " + ioe
.getMessage());
}
}
}
java 边读边写 文件迁移
猜你喜欢
转载自510221952.iteye.com/blog/2401002
今日推荐
周排行