gpt4 book ai didi

java - UTF8 兼容性

转载 作者:行者123 更新时间:2023-11-30 11:10:38 27 4
gpt4 key购买 nike

我正在使用一个函数通过 FTP 将一个文件上传到我的服务器。这是我的代码并且工作正常但是创建的文件 example.json 不兼容 UTF8,因为它有 Atlético 而不是 Atlético 例如。有人可以告诉我这有多正确吗?谢谢

public static void subir(){
String server = myserver;
int port = 21;
String user = mouser;
String pass = mypass;

FTPClient ftpClient = new FTPClient();
try {

ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();

ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

// Uploads first file using an InputStream
File firstLocalFile = new File("example.json");

String firstRemoteFile = "MyDir/example.json";
InputStream inputStream = new FileInputStream(firstLocalFile);

System.out.println("Subiendo archivo a servidor...");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
if (done) {
System.out.println("Subido perfectamente");
}


} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

}

为了保存我使用的文件

public static void guardar(){
FileOutputStream fop = null;
File file;
String content = sBuffer.toString();

try {

file = new File("example.json");
fop = new FileOutputStream(file);

// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
else{
file.createNewFile();
}

// get the content in bytes
byte[] contentInBytes = content.getBytes();

fop.write(contentInBytes);
fop.flush();
fop.close();

System.out.println("Archivo guardado");
subir();

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

最佳答案

关键部分是将 String 转换为 byte 序列。

在你的例子中,这是一行

byte[] contentInBytes = content.getBytes();

当您调用 String.getBytes() 时,它会使用您所在区域的编码,根据您的观察,这似乎不是 UTF-8。如果要使用特定的编码,则需要指定编码。你可以使用

byte[] contentInBytes = content.getBytes(StandardCharsets.UTF_8);

但是,在我看来,问题不在于如何将 Java 字符串转换为 UTF-8,而在于如何解释 UTF-8 字符串。

字节序列41 74 6c c3 a9 74 69 63 6f

  • Atlético 当解释为 ISO-8859-1 时
  • Atlético 当解释为 UTF-8 时

对我来说,问题似乎出在解释转换后的字符串的代码或程序上,而不是在 Java 程序中进行转换(不过,如果您需要它是 UTF-8,请修复它,这样它就不会依赖于区域设置)。

顺便说一句,如果您想将文本(不是二进制数据)保存到文件中,您可能需要使用 Writer 而不是 OutputStream。以下方法演示了如何使用 UTF-8 将字符串写入文件。

import java.nio.charset.StandardCharsets;

public static void save(final File file, final String text) throws IOException {
try (final OutputStream fout = new FileOutputStream(file);
final Writer out = new OutputStreamWriter(fout, StandardCharsets.UTF_8)
) {
out.write(text);
}
}

关于java - UTF8 兼容性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27648369/

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