我正在使用write()方法写入外部存储的文件。该方法只接受byte []作为输入。我曾尝试传递一个字符串,并且我收到一条错误消息(“类型FileOutputStream中的方法write(int)不适用于参数String”)。如果我传递一个int,我不会收到错误,但是在文件中没有写入任何内容。我从调用getNumSentPackets()得到的值是一个int,我需要将它转换为byte []。我一直在寻找已经在这里回答的其他问题,并且我尝试了ByteBuffer选项,但是我在文件中得到的结果并不是我想要的,这意味着我没有收到发送数据包的数量。有人可以帮我吗?在Android中将int转换为byte []
这是我的代码:
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
号码仅仅是一个例子,这就是我希望看到的有一个数字对应于发送的数据包总数。
预先感谢您。
您能否在您的问题中添加完整的预期输出? – SirDarius 2014-10-31 09:38:32
这就是我期待 驱结果文件 发送报文数 200是一个例子,但我想有numSentPackets – 2014-10-31 09:41:11
我问你更新你的问题的价值,因为使用对此的评论丢弃所有换行符;) – SirDarius 2014-10-31 09:44:07