サーバーから送信された情報を使用して、ソケットを使用してコンピューター上のファイルを更新するプログラムがあります。私がそれを機能させた方法ですが、私はそれをより直感的で、より単純で、より信頼できるものにしたかったのです。これが前のコードです:
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
私はいくつかのグーグル検索をしました、しかし私は私が尋ねるべき正しい質問を知っているように感じません。どんな助けでも素晴らしいでしょう!前もって感謝します!!!