Wednesday, May 26, 2010

Split a file

Reqmt : The input file will have a some text, each text delimited by a '$' sign. We need to separate each text to a new file, each new file is appended by'-1', '-2' depending on teh no. of texts it has. If the file has only one text message the original name should remain intact. We need to push the new files into a new path and delete the original ones from the input folder.

public class SplitFile {
public static void main(String[] args) {
/*args = new String[2];
args[0] = "C:/HOMEWARE/reports/swift/"; // input file path
args[1] = "C:/HOMEWARE/reports/extract/"; // output file path*/
try {
File directory = new File(args[0]);
/*Get the list of files in the swift directory*/
String filename[] = directory.list();
String listFilenames=null;
String inputFileName;
String outputFileName;
StringBuffer contents;
/*Iterate the directory for each SWIFT file*/
for (int i = 0; i < filename.length; i++) {
listFilenames = filename[i];
inputFileName=args[0]+listFilenames;
outputFileName=args[1]+listFilenames;
String line = null;
contents=new StringBuffer();
/*Return if the file is not available*/
File is = new File(inputFileName);
if(!is.exists()){
System.err.println("File " + inputFileName+ " not present to begin with!");
break;
}
BufferedReader input = new BufferedReader(new FileReader(inputFileName));
/*Get the contents of the file*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
input.close();
/*Separate each SWIFT message based on the delimiter '$'*/
int count=0;
if(null != contents && contents.length() >0) {
FileOutputStream fop = null;
String str= null;
StringTokenizer token = new StringTokenizer(contents.toString(),"$");
while(token.hasMoreTokens()){
str= token.nextToken().toString();
if(!("\r\n".equals(str))){
count++;
fop = new FileOutputStream(outputFileName + "-"+ count);
fop.write(str.getBytes());
}
}
fop.flush();
fop.close();
}
/*If the file contains only one swift messasge, rename the file to its original name*/
if(count == 1){
File renameFile = new File(outputFileName + "-"+ count);
renameFile.renameTo(new File(outputFileName));
}
/*Delete the original file*/
System.out.println("inputFileName :"+inputFileName);
if(is.delete()){
System.out.println("** File " + inputFileName+ " deleted **");
}else{
System.err.println("Failed to delete " + inputFileName);
}
}
} catch (FileNotFoundException e) {
System.out.println("File not present to begin with!");
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Request not completed due to technical issues. Please contact IT team");
}
}
}