有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java试图在Android中通过socket发送utf8格式的xml

我有一个Android应用程序,可以向服务器发送xml文件。如果我将xml头的编码设置为utf-8,它就会一直工作,直到出现一个奇怪的字符,比如日语符号,在这种情况下,服务器会拒绝xml,因为它不是utf-8。我无法控制服务器的工作方式,但它是一个成熟的产品,因此它不是他们的最终产品

在发送xml之前,我将包含它的字符串打印到终端,所有字符都正确显示

我如何知道我创建的字符串是否真的是utf-8,如果是,我如何通过socket将其作为utf-8发送

以下是我将文件读入字符串的方式:

file = new File (filePath);
FileReader fr = new FileReader (file);
BufferedReader br = new BufferedReader(fr);

// Reading the file
String line;
while((line=br.readLine())!=null)
data += line + '\n';
br.close();

这就是我发送字符串的方式

Socket socketCliente = new Socket();

try {
  socketCliente.connect(new InetSocketAddress(address, port), 2000);
} catch (UnknownHostException e) {
      getError("Host doesn't exist");
  return -1;
} catch (IOException e) {
  getError("Could not connect: The host is down");
  return -1;
}

DataOutputStream serverOutput = null;

try {
  serverOutput = new DataOutputStream(socketCliente.getOutputStream());
} catch (IOException e1) {
  getError("Could not get Data output stream");
}

try {
serverOutput.writeBytes(data);
} catch (IOException e) {
getError("Could not write on server");
}

如果在发送之前打印“数据”字符串,所有字符都会正确显示

我尝试了无数种不同的方法来读入字符串,并以不同的方式写入socket,但它们要么没有任何区别,要么就连标准字符也无法完全接受xml

已解决: 我没有将文件读取为字符串,而是将其读取为字节数组,然后将其发送

file = new File(filePath);
    int size = (int) file.length();
    data = new byte[size];
    try {
         BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
         buf.read(data, 0, data.length);
         buf.close();
    } catch (FileNotFoundException e) {
         getError("File not found");
    } catch (IOException e) {
         getError("Could not read from file");
    }

共 (1) 个答案

  1. # 1 楼答案

    Java通常使用UTF-16进行编码。具体来说,要使用UTF-8,您应该使用InputStreamReader(使用FileInputStream)和PrintWriter(使用套接字的OutputStream),并使用构造函数的变体来指定所需的字符集(在本例中为UTF-8)

    如果在应用程序中使用Guava,可以使用几个实用程序来帮助实现这一点,包括文件。newReader()和字节流。复制()