1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* FileSplitter.java by HackTrack
*/
public class FileSplitter {
private static File destDir;
public static File[] splitFile(String filePath, long maxSize, String toDir)
throws IOException {
handleToDir(toDir);
int cpt;
cpt=1;
File[] splittedFiles;
List<File> files = new ArrayList<File>();
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String fileName = new File(filePath).getName();
StringBuffer fileContent = new StringBuffer();
String line;
File currentFile = FileSplitter.createSplittedFile(fileName,(int) cpt);
while ((line = reader.readLine()) != null) {
cpt=cpt+1;
fileContent.append(line);
fileContent.append("\r\n");
if (fileContent.length() >= maxSize) {
FileSplitter.writeFile(currentFile, fileContent.toString());
files.add(currentFile);
fileContent = new StringBuffer();
currentFile = FileSplitter.createSplittedFile(fileName,(int) cpt);
}
}
FileSplitter.writeFile(currentFile, fileContent.toString());
files.add(currentFile);
splittedFiles = new File[files.size()];
int c=0;
for (File file : files) {
splittedFiles[c] = files.get(c);
c++;
}
return splittedFiles;
}
private static void handleToDir(String toDir) {
destDir = new File(toDir);
if (destDir.exists())
destDir.delete();
destDir.mkdir();
}
private static File createSplittedFile(String fileName, int index)
throws IOException {
return File.createTempFile(new File(fileName).getName().substring(0, new File(fileName).getName().indexOf(".")) + "_" + String.valueOf(index),".txt", destDir);
}
private static void writeFile(File destFile, String content)
throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(destFile));
writer.write(content);
writer.flush();
writer.close();
writer = null;
}
public static void main(String[] args) {
try {
// 1048576 = 1Mo
System.out.println(FileSplitter.splitFile("c:/essai.txt", 131072,"c:/testSplit").length+ " files generated");
} catch (IOException e) {
e.printStackTrace();
}
}
} |
Partager