【问题标题】:Converting int to byte[] in android在android中将int转换为byte []
【发布时间】:2014-10-31 09:33:53
【问题描述】:

我正在使用 write() 方法来写入外部存储的文件。此方法仅接受 byte[] 作为输入。我尝试传递一个字符串,但我收到一条错误消息(“FileOutputStream 类型中的方法 write(int) 不适用于参数字符串”)。如果我传递一个 int,我不会收到错误,但在文件中没有写入任何内容。我通过调用 getNumSentPackets() 得到的值是一个 int,我需要将它转换为 byte[]。我一直在查看这里已经回答的其他问题,并且我尝试了 ByteBuffer 选项,但我在文件中得到的结果不是我想要的,这意味着我没有得到发送数据包的数量。有人可以帮帮我吗?

这是我的代码:

     public void createFile(String name) {

    try {
      String filename = name;
      File myFile = new File(Environment.getExternalStorageDirectory(), filename);
      if (!myFile.exists())
        myFile.createNewFile();
      String title = "FLOODING RESULTS FILE\n\n";
      String sent = "Number of sent packets\n";
      FileOutputStream fos;
      byte[] data = title.getBytes();
      byte[] intSent = sent.getBytes();
      int numSent = mSender.getNumSentPackets();
      byte[] numSentBytes = ByteBuffer.allocate(10).putInt(numSent).array();
      try{
      fos = new FileOutputStream(myFile);
      fos.write(data);
      fos.write(intSent);
      fos.write(numSentBytes);
      fos.flush();
      fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
}

public static int getNumSentPackets() {
  return nSentPackets;
}

预期的输出文件如下:

洪水结果文件

发送包数200

200 只是一个示例,这意味着我希望看到一个与发送数据包总数相对应的数字。

提前谢谢你。

【问题讨论】:

  • 能否在您的问题中添加完整的预期输出?
  • 这是我所期望的 FLOODING RESULTS FILE Number of sent packet 200 200 是一个例子,但我想要 numSentPackets 的值
  • 我要求您更新您的问题,因为对此使用评论会丢弃所有换行符;)
  • 我可以不简单地在文件中打印一个 int 并忘记所有这些转换过程吗?

标签: android


【解决方案1】:

由于我是一个懒惰的开发人员,我喜欢在我选择的语言中使用现有工具,例如,对于 java,PrintWriter

public void createFile(String filename) {
    try {
      File myFile = new File(Environment.getExternalStorageDirectory(), filename);

      PrintWriter out = new PrintWriter(myFile); // this will create the file if necessary

      out.println("FLOODING RESULTS FILE");
      out.println();
      out.print("Number of sent packets ");
      out.println(mSender.getNumSentPackets());
      out.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

这比您当前的方法更易于阅读和维护,并且看起来更惯用。

【讨论】:

  • 非常感谢!这行得通!我对 android 和 java 完全陌生,我并不真正了解 java 提供的设施。谢谢!!
【解决方案2】:
ByteBuffer.allocate(capacity).putInt(yourInt).array();

【讨论】:

  • 感谢您的回答,但也许您看错了。如果您阅读我的帖子并查看我的代码,您会发现我正在使用它并且我没有得到我期望的结果。相反,我得到一大堆我认为是十六进制的数字。
【解决方案3】:

“200”的文本表示要求您写 3 个字符。所有文件最终都只是一堆字节,因此需要从字符到某个字节值的映射。假设ASCII(*) 写入文件的数据为

//                    '2','0','0'
byte[] textVersion = { 50, 48, 48 } 

另一方面,int 是一个 32 位的数值,即有 4 个字节,200 相当于

byte[] intVersion = { 0, 0, 0, 200 }

使用ByteBuffer 时,您会得到这个。如果您将其写入文件并且文本查看器尝试显示它会显示类似◻◻◻Č 的内容,如果您幸运的话。 0 实际上是一个不可打印的控制字符,因此在打印时经常被跳过或替换为看起来很奇怪的字符,如框。 200 相当于 Windows-CP1250 中的 Č。当解释为 UTF8 时,它本身没有任何意义 - 它是 2 字节序列的开始,因此需要接下来的 2 字节来确定要显示的字符。

你可以使用

String.valueOf(200).getBytes( /* you should specify which encoding to use here */ );

这将首先创建 "200" 字符串,然后返回这 3 个字符所需的字节。

但是,您应该使用 Java 的基于字符的 IO 工具:众多(且令人困惑的)ReaderWriter 实现。他们都(*^2)最后包装了InputStreamOutputStream,并为您进行文本到字节的转换。

PrintWriter 可能是最方便使用但并非没有缺陷:https://stackoverflow.com/a/15803472/995891 FileWriter 应该避免,因为你不能指定编码

更长的替代路线是

BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(
             new FileOutputStream(file), encoding));
writer.write("Hello ");
writer.write(String.valueOf(200));
writer.newLine();

(*) 大多数编码与前 127 个字符的 ASCII 兼容,基本上涵盖了正常的英文文本。

(*^2) 没有任何东西会强制 Writer 将字符输出到流中,例如StringWriter。但它们大多是这样使用的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2020-02-03
    • 2011-08-19
    • 1970-01-01
    • 2010-11-08
    相关资源
    最近更新 更多