查找下面的几个步骤
public static void main(String[] args) throws Exception {
// read all lines into a list of strings
List<String> lines = Files.readAllLines(Paths.get("data.txt"),
StandardCharsets.UTF_8);
// use the first string to generate the INSERT statement
// without the values
String insertLine = createInsertLine(lines.get(0));
try (BufferedWriter bw = Files.newBufferedWriter(Paths.get("data.sql"),
StandardCharsets.UTF_8)) {
bw.write(insertLine);
bw.write(System.lineSeparator());
int lastValueId = lines.size() - 1;
for (int i = 1; i <= lastValueId; i++) {
// create from each following line the VALUES part
// of the INSERT statement
String valueLine = createValueLine(i, lines.get(i));
// write the lines into the file
bw.write(valueLine);
bw.write(i == lastValueId ? ';' : ',');
bw.write(System.lineSeparator());
}
}
}
private static String createValueLine(int id, String line) {
// split the values in the line on the '|' character
// including leading and trailing blanks
String[] columns = line.split(" *\\| *");
// construct the VALUES line
StringBuilder valueLine = new StringBuilder();
// start with the ID value
valueLine.append("(").append(id).append(", ");
// append all column values, except for the last column
for (int i = 0; i < columns.length - 1; i++) {
valueLine.append('\'')
.append(columns[i])
.append("', ");
}
// append the last column value and the end of the line
valueLine.append('\'')
.append(columns[columns.length - 1])
.append("')");
return valueLine.toString();
}
private static String createInsertLine(String line) {
String[] columns = line.split(" *\\| *");
StringBuilder insertLine = new StringBuilder();
insertLine.append("INSERT INTO 'events' ('id', ");
for (int i = 0; i < columns.length - 1; i++) {
insertLine.append('\'')
.append(columns[i])
.append("', ");
}
insertLine.append('\'')
.append(columns[columns.length - 1])
.append("') VALUES");
return insertLine.toString();
}
假设该文件data.txt
解释工作段包含
Selected | Status | Event | File
Yes | Listed | Birthday | bday.pdf
No | Not Listed | Gifts | gifts.pdf
生成的data.sql
将
INSERT INTO 'events' ('id', 'Selected', 'Status', 'Event', 'File') VALUES
(1, 'Yes', 'Listed', 'Birthday', 'bday.pdf'),
(2, 'No', 'Not Listed', 'Gifts', 'gifts.pdf');
只需在每行中用','替换'|'。 – Satya
@Satya谢谢,但读取文本文件没有错,输出仍显示'|'。我被困在如何将文本文件转换为sql文件,如上面给出的示例输出 –
'|'是正则表达式中的一个特殊字符。像'// |'一样使用。 – Satya