【发布时间】: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