gpt4 book ai didi

java - 如何使用GBK编码将汉字写入文本文件?

转载 作者:行者123 更新时间:2023-12-02 12:09:40 49 4
gpt4 key购买 nike

我有一张表,其中一列有汉字。我尝试使用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();
}

最佳答案

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

<javac encoding="GBK" ...>

尝试这样做,它会对您有所帮助。

关于java - 如何使用GBK编码将汉字写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46630078/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com