Java更新程序问题
我有一个程序,使用服务器发送的信息,使用套接字更新计算机上的文件。我让它工作的方式,但我想让它更直观、更简单、更可靠,等等。下面是前面的代码:Java更新程序问题,java,file,sockets,object,updates,Java,File,Sockets,Object,Updates,我有一个程序,使用服务器发送的信息,使用套接字更新计算机上的文件。我让它工作的方式,但我想让它更直观、更简单、更可靠,等等。下面是前面的代码: int filesize = 6022386; // filesize temporary hardcoded int bytesRead; int current = 0; /** * receive file */ try { byte[] byteArray = new by
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块中的大部分代码替换为:
FileOutputStream fileOutStream = new FileOutputStream(
UpdateObject.getDirectory()+"\\NPS Game.txt");
fileOutStream.write(UpdateObject.getBytes()); //this is the byte[] array
fileOutStream.close();
希望这能有所帮助。很高兴知道这有帮助。