【问题标题】:ObjectOutputStream.writeUTF writes corrupt characters at the startObjectOutputStream.writeUTF 在开始时写入损坏的字符
【发布时间】:2019-06-01 15:40:50
【问题描述】:

这是我的 .json 文件:

{"Usuarios":[{"password":"admin","apellido":"Admin","correo":"Adminadmin.com","direccion":"Admin","telefono":"Admin","nombre":"Admin","username":"admin"}]}

(我尽量在 cmets 中将我的代码从西班牙语翻译成英语

JSON 中写的函数是这个:

 public void agregarUsuario(String nombre, String apellido, String direccion, String telefono, String correo, String username, String password) {
    try {
        //String jsonString = JsonObject.toString();

        JSONObject usuarios = getJSONObjectFromFile("/usuarios.json"); 
        JSONArray listaUsuario = usuarios.getJSONArray("Usuarios");     
        JSONObject newObject = new JSONObject();                        
        newObject.put("nombre", nombre);
        newObject.put("apellido", apellido);
        newObject.put("direccion", direccion);
        newObject.put("telefono", telefono);
        newObject.put("correo", correo);
        newObject.put("username",username);
        newObject.put("password", password);

        listaUsuario.put(newObject);                                    
        usuarios.put("Usuarios",listaUsuario);  

        ObjectOutputStream outputStream = null;

        outputStream = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Victor\\eclipse-workspace\\Iplane\\assets\\usuarios.json"));

        outputStream.writeUTF(usuarios.toString());
        outputStream.flush();
        outputStream.close();

    }catch(JSONException e) {
        e.printStackTrace();
    }catch(Exception e) {
        System.err.println("Error writting json: " + e);
    }

所以,如果在我的“创建用户”JFrame 窗口中,我在所有用户详细信息中使用“asdf”作为信息创建了一个新用户,我应该得到以下 JSON 文件:

{"Usuarios":[{"password":"admin","apellido":"Admin","correo":"Adminadmin.com","direccion":"Admin","telefono":"Admin","nombre":"Admin","username":"admin"},{"password":"asdf","apellido":"asdf","correo":"asdf","direccion":"asdf","telefono":"asdf","nombre":"asdf","username":"asdf"}]}

是的!那个会发生!但如果我的 JSON 主要对象,我也会在前面得到一些奇怪的 ascii/Unicode 符号。我不能在这里复制输出,所以这是我在 imgur 上的输出:link

为什么会出现这个问题?我该如何解决? 如果有人需要我的 json 文件阅读器(也许问题就在那里),你可以去:

    public static InputStream inputStreamFromFile(String path) {
    try {
        InputStream inputStream = FileHandle.class.getResourceAsStream(path); //charge json in "InputStream"
        return inputStream;
    }catch(Exception e) {
        e.printStackTrace(); //tracer for json exceptions
    }
    return null;
}
 public static String getJsonStringFromFile(String path) {
        Scanner scanner;
        InputStream in = inputStreamFromFile(path); //obtains the content of the .JSON and saves it in: "in" variable
        scanner = new Scanner(in);                              //new scanner with inputStream "in" info
        String json= scanner.useDelimiter("\\Z").next();        //reads .JSON and saves it in string "json"
        scanner.close();                                        //close the scanner
        return json;                                            //return json String
     }
 public static boolean objectExists (JSONObject jsonObject, String key) { //verifies whether an object exist in the json
     Object o;
     try {
         o=jsonObject.get(key);
     }catch(Exception e) {
         return false;
     }
     return o!=null;
 }

  public static JSONObject getJSONObjectFromFile(String path) {    //creates a jsonObject from a path
     return new JSONObject(getJsonStringFromFile(path));
 }

因此,在写入 JSON 文件后,我无法对其进行任何操作,因为有了这个奇怪的符号,我的 json 中出现错误:“extraneus input: (here are the symbols) expecting [STRING, NUMBER, TRUE, FALSE , {..."

【问题讨论】:

  • ObjectOutputStream 不适用于编写文本或 JSON。 writeUTF 方法不会写入真正的 UTF-8 文本。请改用OutputStreamWriter
  • 嗨,欢迎来到 StackOverflow。如果您还没有,请在帮助中心查看How do I ask a good question?。为了使这个问题成为一个很好的问题,如果输出对于任何 String 或仅对于您尝试的 JSON 来说都很有趣,并且 minimal example 会在没有所有 JSON 分散真正问题的注意力的情况下工作(错误的 OutputStream writer被选中)。请考虑修改您的问题,以便其他有类似问题的人更快地学习/找到他们的解决方案:)
  • 如果您有问题或需要帮助,我会在我为您创建的聊天室里闲逛一段时间:chat.stackoverflow.com/rooms/186278/…

标签: java utf-8 java-io


【解决方案1】:

writeUTF 不编写标准 unicode,而是在输出前添加两个字节的长度信息

如果你故意使用writeUTF,你必须使用readUTF再次读取数据。否则我建议使用OutputStreamWriter

writeUTF()

将两个字节的长度信息写入输出流,紧随其后 通过字符串中每个字符的修改后的 UTF-8 表示 s。如果 s 为 null,则抛出 NullPointerException。中的每个字符 字符串 s 被转换为一组一个、两个或三个字节, 取决于字符的值。


** 编辑澄清OutputStreamWriter

要使用OutputStreamWriter,只需将ObjectOutputStream 替换为OutputStreamWriter 并使用write 而不是writeUTF

您可能会发现这个小教程很有帮助:Java IO: OutputStreamWriter on jenkov.com

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 2021-07-30
  • 2019-06-03
  • 1970-01-01
相关资源
最近更新 更多