File Split - gsnaidujava/pp GitHub Wiki
package com.firstdata;
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.Scanner;
public class FileSplit {
private final static String NEWLINE = System.getProperty("line.separator");
public void splitFile(String inputFile, String outputPath) throws IOException {
Scanner scanner = new Scanner(new File(inputFile)); BufferedReader bufferReader = new BufferedReader(new FileReader( inputFile)); int numberOfLines = 0; // to find number of lines for a given input file. while ((bufferReader.readLine()) != null) { numberOfLines++; } while (scanner.hasNextLine()) { StringBuffer data = null; Boolean flag = false; int count = 1; String header = "HEDR"; String footer = "FOOT"; // bufferWriter object for writing the data to a file. BufferedWriter bufferedWriter = null; // iterating the number of lines. for (int i = 1; i <= numberOfLines; i++) { try { String line = scanner.nextLine(); String temp = line.substring(0, 4); /* * if first 4 bytes of any line equal to header then * creating the new file and appending the data to the * string buffer object. */ if (header.equals(temp)) { data = new StringBuffer(); bufferedWriter = new BufferedWriter(new FileWriter( outputPath + "DOM_PIF_06172014-" + count + ".txt")); data.append(line + NEWLINE); count++; flag = true; } else if (flag) { /* * if any 4 bytes of line equal to footer, appending the * data to the string buffer object and writing the data * to a file. */ if ((footer.equals(temp))) { flag = false; data.append(line); bufferedWriter.write(data.toString()); bufferedWriter.close();
} else { data.append(line + NEWLINE); } } } catch (Exception e) { break; } } }
}
public static void main(String ar[]) throws Exception {
FileSplit fileSplit = new FileSplit();
fileSplit.splitFile( "C:\\Development\\Documents\\Micro\\DOM_PIF_06172014.txt", "C:\\Development\\Documents\\Micro\\output\\"); }
}