将文本文件转换为sql文件

时间:2016-01-21 06:31:00

标签: java

我正在进行一项打开文本文件并转换/另存为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文件?

非常感谢你!

2 个答案:

答案 0 :(得分:1)

修改您的try块,如下所示。 添加了List<String> parseLine(String line)String createInsert(List<String> headers, List<String> rowData)

两个函数

使用简单的String标记化实现第一个,然后通过简单的字符串连接使用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();
    }

答案 1 :(得分:0)

在下面找到一个工作片段,其中包含几个步骤的说明

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');