Actually I had a .rtf file and from that I was trying to create a csv file. While searching I saw that I have convert it into plain text and then to csv file. But right now I am kind of stuck with logic. I am not getting idea what to apply to move forward.
I have below data which I want to convert to csv.
Input :
Search Target Redmond40_MAS Log Written 01/18/2013 9:13:19 Number of attempts 1
Search Target Redmond41_MAS Log Written 01/19/2013 9:15:16 Number of attempts 0
Output :
Search Target,Log Written,Number of attempts
Redmond40_MAS,01/18/2013 9:13:19,1
Redmond41_MAS,01/19/2013 9:15:16,0
If there was any delimiter then I would have done it but in this case I know are the "keys" i.e. header values but not getting the idea how to extract corresponding contents.
Any suggestion will help.
import java.io.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.rtf.RTFEditorKit;
public class Rtf2Csv {
public static void main(String[] args) {
RTFEditorKit rtf = new RTFEditorKit();
Document document = rtf.createDefaultDocument();
try {
FileInputStream fi = new FileInputStream("test.rtf");
rtf.read(fi, document, 0);
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("I/O error");
} catch (BadLocationException e) {
}
String output = "Search Target,Log Written,Number of attempts";
try {
String text = document.getText(0, document.getLength());
text = text.replace('\n', ' ').trim();
String[] textHeaders = text
.split("===================================================================================");
String[] header = { "Search Target", "Log Written",
"Number of attempts"};
System.out.println(textHeaders.length);
int headLen = header.length;
int textLen = textHeaders.length;
for (int i = 0; i < textLen; i++) {
String finalString = "";
String partString = textHeaders[i];
for (int j = 0; j < headLen; j++) {
int len = header[j].length();
if (j + 1 < header.length)
finalString += partString.substring(
partString.indexOf(header[j]) + len,
partString.indexOf(header[j + 1])).trim()
+ ",";
else
finalString += partString.substring(
partString.indexOf(header[j]) + len).trim();
}
output += "\n" + finalString;
}
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileWriter writer = new FileWriter("output.csv");
writer.append(output);
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have written this code. Is there any better way to improve it?