gpt4 book ai didi

Java 更新程序问题

转载 作者:行者123 更新时间:2023-12-01 14:47:26 26 4
gpt4 key购买 nike

我有一个程序,可以使用服务器通过套接字发送的信息来更新计算机上的文件。我的工作方式是这样的,但我想让它更直观、更简单、更可靠等。这是之前的代码:

int filesize = 6022386; // filesize temporary hardcoded

int bytesRead;
int current = 0;

/**
* receive file
*/
try {
byte[] byteArray = new byte[filesize];
java.io.InputStream inStream = socket.getInputStream();
bytesRead = inStream.read(byteArray, 0, byteArray.length);
FileOutputStream fileOutStream = new FileOutputStream(
"C:\\Program Files\\AVTECH\\NPS\\Files\\bin\\NPS Game.txt");
BufferedOutputStream buffOutStream = new BufferedOutputStream(
fileOutStream);
current = bytesRead;

do {
bytesRead = inStream.read(byteArray, current,
(byteArray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);

buffOutStream.write(byteArray, 0, current);
buffOutStream.flush();
buffOutStream.close();
inStream.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
socket.close();
}

如您所见,在 do, while 循环中,它使用输入流来获取数据。现在我已经更新了我的程序,我让流发送一个名为 UpdateObject 的对象,该对象保存 byte[] 数组以及文件目录。这是代码:

    int filesize = 6022386; // filesize temporary hardcoded

int bytesRead;
int current = 0;
try {
byte[] byteArray = o.getFile();
java.io.InputStream inStream = socket.getInputStream();
bytesRead = inStream.read(byteArray, 0, byteArray.length);

FileOutputStream fileOutStream = new FileOutputStream(o.getPath());
BufferedOutputStream buffOutStream = new BufferedOutputStream(
fileOutStream);
current = bytesRead;

do {
bytesRead = inStream.read(byteArray, current,
(byteArray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);

buffOutStream.write(byteArray, 0, current);
buffOutStream.flush();
buffOutStream.close();
inStream.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}

现在我的问题是:我如何更改它,而不是使用instream,而是使用通过套接字发送的UpdateObject中的byte[]对象?我已经做了一些谷歌搜索,但我觉得我不知道要问的正确问题。任何帮助都会很棒!提前致谢!!!

最佳答案

将 try catch block 内的大部分代码替换为:

FileOutputStream fileOutStream = new FileOutputStream(
UpdateObject.getDirectory()+"\\NPS Game.txt");
fileOutStream.write(UpdateObject.getBytes()); //this is the byte[] array
fileOutStream.close();

希望这有帮助。

关于Java 更新程序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15282348/

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