java读写大文件

时间:2024-01-18 19:02:38

java读写2G以上的大文件(推荐使用以下方法)

     static String sourceFilePath = "H:\\DataSource-ready\\question.json" ;
static String distFilePath = "H:\\DataSource-ready\\separate\\" ; public static void main( String[] args )
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
System.out.println("开始时间" + sdf.format(new Date()));// new Date()为获取当前系统时间 long timer = System.currentTimeMillis();
try {
File file = new File(sourceFilePath);
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(fis,"utf-8"),7*1024*1024);// 用7M的缓冲读取文本文件 int count = 1 ;
String outputFile = distFilePath + count + ".json" ;
FileWriter fw = new FileWriter(outputFile);
String line = "";
while((line = reader.readLine()) != null){
if ( line.contains("},") ) {
line = line.replace("},", "}") ;
fw.append(line + "\r");
fw.flush();
fw.close();
count ++ ;
outputFile = distFilePath + count + ".json" ;
fw = new FileWriter(outputFile);
}
else {
fw.append(line + "\r");
}
}
reader.close();
fw.flush();
fw.close();
} catch (IOException e) {
System.out.println("读写文件失败!");
e.printStackTrace();
}
timer = System.currentTimeMillis() - timer;
System.out.println("处理时间:" + timer + " 毫秒");
System.out.println("结束时间:" + sdf.format(new Date()));
}

共同学习,共同进步,若有补充,欢迎指出,谢谢!