JAva行ごとに大きなファイルを分割する
1770 ワード
/**
*
* @param rows
* @param sourceFilePath
* @param targetDirectoryPath
*/
public void splitDataToSaveFile(int rows, String sourceFilePath,
String targetDirectoryPath) {
long start1 = System.currentTimeMillis();
File sourceFile = new File(sourceFilePath);
File targetFile = new File(targetDirectoryPath);
if (!sourceFile.exists() || rows <= 0 || sourceFile.isDirectory()) {
return;
}
if (targetFile.exists()) {
if (!targetFile.isDirectory()) {
return;
}
} else {
targetFile.mkdirs();
}
try {
InputStreamReader in = new InputStreamReader(new FileInputStream(sourceFilePath),"GBK");
BufferedReader br=new BufferedReader(in);
BufferedWriter bw = null;
String str = "";
String tempData = br.readLine();
int i = 1, s = 0;
long start2 = System.currentTimeMillis();
while (tempData != null) {
str += tempData + "\r
";
if (i % rows == 0) {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
targetFile.getAbsolutePath() + "/" + sourceFile.getName() +"_" + (s+1) +".csv"), "GBK"),1024);
bw.write(str);
bw.close();
str = "";
start2 = System.currentTimeMillis();
s += 1;
}
i++;
tempData = br.readLine();
}
if ((i - 1) % rows != 0) {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
targetFile.getAbsolutePath() + "/" + sourceFile.getName() +"_" + (s+1) +".csv"), "GBK"),1024);
bw.write(str);
bw.close();
br.close();
s += 1;
}
in.close();
} catch (Exception e) {
}
}