Unlock a world of possibilities! Login now and discover the exclusive benefits awaiting you.
public static boolean split_file(String filename, int maxpart, String tagname, String roottag, String nsdeclaration){
FileOutputStream fout = null;
PrintStream outstream = null;
Scanner s = null;
int part=0;
int partsize=0;
boolean partnew=true;
String partfile, suffix, token;
partfile = filename.replaceFirst("\\.xml$", "");
try {
s = new Scanner(new FileInputStream(filename),"utf-8");
s.useDelimiter("</" + tagname + ">");
while (s.hasNext()) {
if(partnew){ //begin a new part file
suffix = String.format("_part%04d.xml",part);
fout = new FileOutputStream (partfile + suffix);
outstream = new PrintStream(fout);
if (part>0){ //insert leading tags
outstream.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
outstream.println("<" + roottag + " " + nsdeclaration + ">");
}
partsize=0;
partnew=false;
}
//just append tokens
token = s.next();
outstream.print(token);
//if not last chunk append closing tag
if (token.indexOf("</" + roottag + ">")<0) outstream.println("</" + tagname + ">");
partsize += token.length();
if (partsize > maxpart) { //time to wrap it up
outstream.println("</" + roottag + ">");
outstream.close();
outstream = null;
fout.close();
fout = null;
part++;
partnew = true;
}
}
//dump the remaining part to out
outstream.close();
//fout.close();
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
if (s != null) {
s.close();
}
if (outstream != null) {
outstream.close();
}
return false;
}
}