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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| 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;
public class Eclatement {
private static File destDir;
private static BufferedReader reader;
private static File file;
public static File[] splitFile(String filePath, String toDir)
throws IOException {
handleToDir(toDir);
File[] splittedFiles;
List<File> files = new ArrayList<File>();
reader = new BufferedReader(new FileReader(filePath));
String fileName = new File(filePath).getName();
StringBuffer fileContent = new StringBuffer();
String line;
File currentFile = Eclatement.createSplittedFile(fileName, files
.size());
while ((line = reader.readLine()) != null) {
fileContent.append(line+"\n");
if (line.equals("P*")) {
Eclatement.writeFile(currentFile, fileContent.toString());
//System.out.println(currentFile);
files.add(currentFile);
fileContent = new StringBuffer();
currentFile = Eclatement.createSplittedFile(fileName, files
.size());
}
}
Eclatement.writeFile(currentFile, fileContent.toString());
files.add(currentFile);
splittedFiles = new File[files.size()];
int c=0;
for (int i = 0; i < files.size(); i++) {
setFile(files.get(i));
splittedFiles[c] = files.get(c);
c++;
}
return splittedFiles;
}
/**
* @return the file
*/
public static File getFile() {
return file;
}
/**
* @param file the file to set
*/
public static void setFile(File file) {
Eclatement.file = file;
}
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) {
File file=new File(destDir, fileName); // pas terrible, cette variable destDir statique !!!
String name = file.getName();
int pos = name.lastIndexOf("."); // détection de l'extension
if( pos<0 ) {
// pas d'extension
name += "." + index;
}
else {
name = name.substring(0,pos)+"."+index+name.substring(pos);
}
return new File(file.getParentFile(), name);
}
private static void writeFile(File destFile, String content)
throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(destFile));
writer.write(content);
//System.out.println(content);
writer.flush();
writer.close();
writer = null;
}
public static void main(String[] args) {
try {
// 1048576 = 1Mo
System.out.println(Eclatement.splitFile("C:/Users/user/Desktop/FICHIER.HPR",
"C:/Users/user/Desktop/cible").length
+ " files generated");
} catch (IOException e) {
e.printStackTrace();
}
}
} |
Partager