Java 将文本文件转换为sql文件

Java 将文本文件转换为sql文件,java,Java,我正在做一个作业,打开一个文本文件并转换/另存为sql文件。我知道如何打开一个文本文件,但我被困在如何转换为sql文件 下面是我用来读取文本文件的代码 public static void main(String[] args) { // The path to open the file. String fileName = "input.txt"; String line = null; try {

我正在做一个作业,打开一个文本文件并转换/另存为sql文件。我知道如何打开一个文本文件,但我被困在如何转换为sql文件

下面是我用来读取文本文件的代码

    public static void main(String[] args) {

        // The path to open the file.
        String fileName = "input.txt";
        String line = null;

        try {
            // The file reads text files 
            FileReader file = new FileReader(fileName);

            // Wrap file in BufferedReader
            BufferedReader bufferedReader = new BufferedReader(file);

            while ( (line = bufferedReader.readLine()) != null ) {
                System.out.println(line);
            }

            // Close files
            bufferedReader.close();
        } catch ( FileNotFoundException ex ) {
            System.out.println("Unable to open file '" + fileName + "'");
        } catch ( IOException ex ) {
             ex.printStackTrace();
        }
    }
有谁能给我一些提示,在阅读文本文件后如何将文本文件保存为sql文件


非常感谢你

修改try块,如下所示。 添加了两个函数
List parseLine(String line)
String createInsert(List headers,List rowData)

首先使用简单字符串标记化实现,然后通过简单字符串连接使用createInsert

try {
        // The file reads text files 
        FileReader file = new FileReader(fileName);

        // Wrap file in BufferedReader
        BufferedReader bufferedReader = new BufferedReader(file);
        List<String> headers;
        String line = bufferedReader.readLine();
        if( line !=null ) { //got the row header
             headers = parseLine(line);
        }
        List<String> rowData;
        while ( (line = bufferedReader.readLine()) != null ) {
            rowData = parseLine(line);
            createInsert(headers, rowData);
        }
        // Close files
        bufferedReader.close();
    } catch ( FileNotFoundException ex ) {
        System.out.println("Unable to open file '" + fileName + "'");
    } catch ( IOException ex ) {
         ex.printStackTrace();
    }
试试看{
//该文件读取文本文件
FileReader文件=新的FileReader(文件名);
//在BufferedReader中包装文件
BufferedReader BufferedReader=新的BufferedReader(文件);
列表标题;
String line=bufferedReader.readLine();
如果(line!=null){//得到行标题
headers=parseLine(行);
}
列出行数据;
而((line=bufferedReader.readLine())!=null){
rowData=parseLine(行);
createInsert(标题、行数据);
}
//关闭文件
bufferedReader.close();
}捕获(FileNotFoundException ex){
System.out.println(“无法打开文件“”+fileName+”);
}捕获(IOEX异常){
例如printStackTrace();
}

在下面找到一个工作片段,解释了几个步骤

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();
}
生成的
数据.sql

INSERT INTO 'events' ('id', 'Selected', 'Status', 'Event', 'File') VALUES
(1, 'Yes', 'Listed', 'Birthday', 'bday.pdf'),
(2, 'No', 'Not Listed', 'Gifts', 'gifts.pdf');

只需将每行中的
|
替换为
。@Satya谢谢,但是读取文本文件没有问题,输出仍然显示“|”。我一直在研究如何将文本文件转换为sql文件,因为上面给出的示例输出
是正则表达式中的一个特殊字符。使用like
/|
。非常感谢!你能解释一下关于字符串标记化和CreateSert的更多信息吗?我对这两个术语不太熟悉。非常感谢,它对我来说非常有用。但是我试着像
(1'Yes','Listed','birth','bday.pdf'),
而不是
(1'Yes','Listed','birth','bday.pdf')
插入到“事件”(“id”、“Selected”、“Status”、“Event”、“File”)中的值应仅显示一次作为标题。我怎样才能修好这些?再次感谢@MichaelNg 1)更改
createValueLine
中的
.append(“);”.append(“),”中添加code>2)移动行
bw.write(insertLine)前面的
main
方法中的code>。
您回答了第二部分,非常感谢!但是对于第一个问题,我试着只做最后一行的
最后,它应该像
插入“事件”('id','Selected','Status','Event','File')值(1,'Yes','Listed','birth','bday.pdf'),(2,'No','Not Listed','Gifts','Gifts.pdf')最后,它工作得非常好。非常感谢你的帮助@如果这解决了你的问题,请接受这个答案。
INSERT INTO 'events' ('id', 'Selected', 'Status', 'Event', 'File') VALUES
(1, 'Yes', 'Listed', 'Birthday', 'bday.pdf'),
(2, 'No', 'Not Listed', 'Gifts', 'gifts.pdf');