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.

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

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM