实际上我有一个 .rtf 文件,并且我试图创建一个 csv 文件。在搜索时,我看到我已将其转换为纯文本,然后转换为 csv 文件。但现在我有点被逻辑困住了。我不知道要申请什么才能继续前进。
我有以下要转换为 csv 的数据。
输入 :
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
输出 :
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
如果有任何分隔符,那么我会这样做,但在这种情况下,我知道是“键”,即标题值,但不知道如何提取相应的内容。
任何建议都会有所帮助。
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();
}
}
}
我已经写了这段代码。有没有更好的改进方法?