将文件和数据转换为outputStream,并从inputStream转换为文件和数据



我需要将文件和数据传输到可穿戴设备,并且正在使用ChannelClient。我正在发送各种数据(一个文件和各种变量(,因此getInputStream和getOutputStream似乎是正确的方法(而不是发送文件(。

如何用文件打包变量集合并在outputStream中发送它们,以及如何从inputStream中解压缩它们?

我在使用以下代码时收到此错误:java.lang.ClassNotFoundException: d.b.a.m.a

手机

String node = settingsRepository.getNode();
String path = "/channel/mobile";
ChannelClient channelClient = Wearable.getChannelClient(getContext());
channelClient.openChannel(node,path).addOnSuccessListener(new OnSuccessListener<ChannelClient.Channel>() {
@Override
public void onSuccess(ChannelClient.Channel channel) {
Log.d(TAG, "onSuccess: ");
channelClient.getOutputStream(channel).addOnSuccessListener(new OnSuccessListener<OutputStream>() {
@Override
public void onSuccess(OutputStream outputStream) {
Log.d(TAG, "channelClient.getOutputStream.onSuccess: ");

File file = new File("/data/user/0/com.xxx.yyy/files/icon-8.png");
TestObject testObject = new TestObject("test",file);
Log.d(TAG, "channelClient.getOutputStream.onSuccess: name=" + testObject.getName());
ObjectOutputStream out = new ObjectOutputStream(outputStream);
out.writeObject(testObject);
out.flush();
out.close();
}
})
}
})

我该如何在Wearable上打开它们?

可穿戴

Task<InputStream> inputStreamTask = Wearable.getChannelClient(getApplicationContext()).getInputStream(channel);
inputStreamTask.addOnSuccessListener(new OnSuccessListener<InputStream>() {
@Override
public void onSuccess(InputStream inputStream) {
Log.d(TAG, "addOnSuccessListener.onSuccess: ");

try {
ObjectInputStream in = new ObjectInputStream(inputStream);

TestObject testObject = (TestObject) in.readObject();
Log.d(TAG, "addOnSuccessListener.onSuccess: name=" + testObject.getName());
} catch (Exception e) {
Log.d(TAG, "addOnSuccessListener.onSuccess: error=" + e.getMessage());
e.printStackTrace();
}
}
});

测试对象类

public class TestObject implements Serializable {
String name;
File file;
public TestObject(String name, File file) {
this.name = name;
this.file = file;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}

您可以使用DataOutputStream和DataInputStream。

https://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html

它对类型进行编码,如带前缀的字符串https://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#readUTF((

读取使用修改后的UTF-8格式编码的字符串。readUTF的一般约定是,它读取以修改后的UTF-8格式编码的Unicode字符串的表示;然后将此字符串作为字符串返回。首先,读取两个字节,并使用它来构造一个无符号的16位整数,其方式与readUnsignedShort方法完全相同。这个整数值被称为UTF长度,指定要读取的额外字节数

readFully将读取字节数组。

相关内容

  • 没有找到相关文章

最新更新