如何使用GBK编码将中文字符写入文本文件?

时间:2017-10-08 10:31:02

标签: java character-encoding

我有一张桌子,在一栏中我们有中文字符。我正在尝试使用 GBK 编码将数据写入一个.txt文件,但它是乱码。如果我使用UTF8然后显示正确的中文字符,但我不想使用UTF8。

String url = "jdbc:oracle:thin:@localhost:1521:TEST";
        String user = "testUser";
        String pwd = "testUser";
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection conn = DriverManager.getConnection(url, user, pwd);
        String sql = "Select *from test_table where id=1234";
        PreparedStatement stmt = conn.prepareStatement(sql);
        ResultSet resultSet = stmt.executeQuery();
        String fileName = "C:\\temp\\aaaa.txt";
        try (FileOutputStream os = new FileOutputStream(fileName)) {
            PrintWriter pw = null;
            pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "GBK")));
            String[] data = new String[5];
            String line;
            while (resultSet.next()) {
                data[0] = resultSet.getString(1);
                data[1] = resultSet.getString(2);
                data[2] = resultSet.getString(3);
                data[3] = resultSet.getString(4);
                data[4] = resultSet.getString(5);
                line = setLine(data);
                System.out.println(line);
                pw.print(line);
            }
            pw.flush();
        }
    }

    private static String setLine(String[] data) {
        StringBuilder line = new StringBuilder();
        String delim = ",";
        int count= data.length;
        for (int i = 0; i < count; i++) {
            if (i > 0)
                line.append(delim);
            if (data[i] != null) {
                line.append(data[i]);
            }

        }

        return line.toString();
    }

1 个答案:

答案 0 :(得分:1)

您是否在build.xml中指定了任务的编码选项?

<javac encoding="GBK" ...>

尝试这样做可以帮到你。