This function can be used to split large files containing HL7 message into a seperate file for each message (MSH). Note that JavaScript requires function to be defined before they are called so the Java code is organized in a simular manner to make it easier to view the differences in a diff tool. This should demonstrate some of the changes needed to convert to JavaScipt. The filenaming was changed to use the qie.getUUID() call instead of a counter. This is a simple example but, it highlights a few things to watch for... Please fill free to add issues when converting to this question.
Java Code:
package com;
import java.io.*;
/**
* Created with IntelliJ IDEA.
* User: rconover
* Date: 9/6/13
* Time: 9:47 AM
*/
public class SplitFile {
private static void saveFile(StringBuffer stringBuffer, String filename) {
File file = new File(filename);
FileWriter output = null;
try {
output = new FileWriter(file);
output.write(stringBuffer.toString());
System.out.println("file " + filename + " written");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public static void readFileData(String path, String filename) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
String line;
int counter = 1;
StringBuffer stringBuffer = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("MSH") && stringBuffer.toString().startsWith("MSH")) {
saveFile(stringBuffer, filename + counter);
stringBuffer = new StringBuffer();
counter++;
}
stringBuffer.append(line);
stringBuffer.append(System.getProperty("line.separator"));
}
saveFile(stringBuffer, filename + counter);
bufferedReader.close();
}
public static void iterateOverFilesIn(final File folder) throws IOException {
File[] files = folder.listFiles();
String path = folder.getAbsolutePath() + "\\";
for (int i = 0; i < files.length; i++) {
File fileEntry = files[i];
if (fileEntry.isFile()) {
System.out.println(fileEntry.getName());
String fileName = fileEntry.getAbsolutePath();
if (fileName.endsWith(".big")) {
try {
readFileData(path, fileName);
fileEntry.renameTo(new File(fileName + ".complete"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) throws IOException {
System.out.println("Split function starting...");
final File folder = new File("C:\\temp\\split");
iterateOverFilesIn(folder);
System.out.println("Split function complete.");
}
}
See the next answer for the converted code.