gpt4 book ai didi

java - 将字节数组存储在对象中,然后将其转换为 ObjectOutputStream? (卡住)

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:45:17 24 4
gpt4 key购买 nike

我有点被这个问题困住了。

我有这个 FileDetails 类,它存储文件的详细信息/元数据以及字节数组中的完整文件。我想通过网络发送 ObjectOutputStream 中的 FileDetails 对象,接收者将在其中简单地读取文件并将其投回 FileDetails。

代码如下:

class FileDetails {

private String fileName;
private long fileSize;
private byte[] fileData;

public FileDetails(String fileName, long fileSize, byte[] fileData) {
this.fileName = fileName;
this.fileSize = fileSize;
this.fileData = fileData;
}

public String getFileName() {
return fileName;
}

public long getFileSize() {
return fileSize;
}

public byte[] getFileData() {
return fileData;
}

}


File file = new File("C://test.dat");
RandomAccessFile randFileAccess = new RandomAccessFile(file, "r");
byte[] buff = new byte[(int) file.length()];
randFileAccess.readFully(buff);

FileDetails fd = new FileDetails(file.getname(), file.length(); buff);

FileOutputStream fos = = new FileOutputStream(C://oos.dat);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(fd);
oos.write(buff);

问题是文件“test.dat”非常大,一次性将其完全读入缓冲区(非常大)并不是最佳选择。我本可以阅读将文件分块放入缓冲区,但这需要我创建文件并将数据保存到磁盘中,我不能这样做,因为 FileDetails 对象采用字节数组。

我该如何解决这个问题?我只想要这种方法,即将数据作为字节数组存储在 FileDetails 对象中,然后将其转换为 ObjectOutputStream,因为我将追加附加一个 mp3 文件通知 ObjectOutStream 文件并通过互联网发送它。

有什么建议吗?或者替代方法?

编辑: 实际上我正在开发一个 Android 应用程序。它将文件的元数据与字节数组中的文件数据一起存储在 FileDetails 对象中。此 FileDetails 对象被转换为 ObjectOutputStream 文件。现在在这个 ObjectOutputStream 文件前面附加了一个特定的 mp3 文件,用于识别该文件已由我的应用程序发送。这个组合的 mp3 文件(包含“隐藏的”ObjectOutputStream 文件)通过“流行”的消息应用程序发送到接收方。接收者通过他的“流行”消息应用程序下载 mp3 文件。现在我的应用程序开始运行了。它识别 mp3 文件。并从 mp3 文件中提取 ObjectOutputStream 文件。并将其转换回 FileDetails 并使用其元数据检索原始文件。我的方法正确吗?有没有其他方法可以识别我的附加/隐藏文件?

非常感谢。

最佳答案

是否可以将类添加到接收器中?然后你可以尝试这样的事情:

File file = new File("C://test.dat")
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
-> send over the network
finally {
if (in != null) {
in.close();
}
}
}

接收方可以只将字节写入一个临时文件(而不是将它们保存在内存中)

InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("C://test.dat");
BufferedOutputStream bos = new BufferedOutputStream(fos);
//something like:
byte[] buffer = new byte[1024];
int len = is.read(buffer);
while (len != -1) {
bos.write(buffer, 0, len);
len = is.read(buffer);
}

如果操作完成,实例化对象 FileDetails fd = new FileDetails(the file you just created,....)

如果需要,您也可以通过网络发送类定义。

关于java - 将字节数组存储在对象中,然后将其转换为 ObjectOutputStream? (卡住),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28394558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com