dongting7352 2016-07-13 19:20
浏览 82
已采纳

Golang:将元帅xml写入文件

I have a byte array of marshalled XML, if I write it to a file using the os library:

fh, _ := os.OpenFile("filename", os.O_CREATE, 0644)
_, err := fh.Write(XMLByteArray)

I get a bunch of junk at the end of the file as if it was a bad write:

<project version="4">
  <component name="test">
    <option name="urls">
      <list></list>
    </option>
  </component>
</project>    </option>
  </component>
</project>on>
            </component>
    </project>

If I write it with io/ioutil library like this:

err = ioutil.WriteFile("filename", XMLByteArray, 0644)
    if err != nil {
        log.Fatal(err)
    }

I get proper XML:

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="test">
    <option name="urls">
      <list></list>
    </option>
  </component>
</project>

Here's the part I really don't understand. This file is the result of a dynamic path generation, and is the configuration for IntelliJ. If I use os.Write() and then properly close the file handler, IntelliJ reads the file immediately, but errors out because the XML is messed up. If I write the file with ioutil.WriteFile(), the file looks correct, but IntelliJ isn't recognising the file to exist.

So my questions are:

  1. What is the difference between os.Write() and ioutil.WriteFile()?
  2. Why is that difference causing the byte array to be written differently?
  • 写回答

1条回答 默认 最新

  • dongping4901 2016-07-13 22:32
    关注

    In the OpenFile call, the file already exists and is being reopened and not truncated. The data written is smaller than the content of the file, so overwrites only the start of the file, leaving junk at the end.

    According to os flags you can truncate the file upon opening:

    os.OpenFile("filename", os.O_CREATE | os.O_TRUNC, 0644)
    

    Or use os.Create().

    This is basically what iotuil.WriteFile is doing (see source).

    IntelliJ might not be able to open the file if it doesn't have sufficient permissions. Try changing permissions to 0666 in the code, and check the file is created with these permissions. Note the permission parameter is ignored if the file already exists. Also, the permissions set when creating a file may be restricted by the umask of the process.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮