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的 byte[] 对象?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 回答