0

サーバーから送信された情報を使用して、ソケットを使用してコンピューター上のファイルを更新するプログラムがあります。私がそれを機能させた方法ですが、私はそれをより直感的で、より単純で、より信頼できるものにしたかったのです。これが前のコードです:

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私はいくつかのグーグル検索をしました、しかし私は私が尋ねるべき正しい質問を知っているように感じません。どんな助けでも素晴らしいでしょう!前もって感謝します!!!

4

1 に答える 1

1

try catch ブロック内のほとんどのコードを次のように置き換えます。

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

お役に立てれば。

于 2013-03-07T21:51:37.497 に答える