简体   繁体   English

Java DataInputStream到图像文件

[英]Java DataInputStream to image file

I am on an homework assignment where I have to connect to a http server and download html files and image files using socket programming. 我正在做作业,必须连接到http服务器并使用套接字编程下载html文件和图像文件。

I am doing fine and is able to download and write both the html and image files correctly. 我做得很好,能够正确下载和写入html和图像文件。 But when I edit the code to meet the requirements of the homework (webpages must work locally, so the code is edited to rewrite the html, the image files are not being written to correctly. 但是,当我编辑代码以满足作业要求时(网页必须在本地工作,因此对代码进行了编辑以重写html,因此图像文件未正确写入。

I do not remember editing the code for the method to download the image. 我不记得编辑用于下载图像的方法的代码。 I just checked my files when I thought I was done, and the image showed an invalid image. 我以为自己做完了就检查了文件,并且图像显示无效的图像。

The bytes (when i open the correct image and the download image side by side in notepad++), the bytes are the same. 字节(当我在notepad ++中并排打开正确的图像和下载图像时),字节相同。 The problem is that on the downloaded image, the bytes are written to as one long line, while in the correct image, the bytes are written line by line. 问题在于,在下载的映像中,字节被写成一长行,而在正确的映像中,字节被一行一行地写入。

Tried several different methods, and both didnt work. 尝试了几种不同的方法,但都没有起作用。 In fact, an old code which I sent to a friend (before the editing above) didnt seem to work either. 实际上,我发送给朋友的旧代码(在进行上述编辑之前)似乎也不起作用。 Any ideas? 有任何想法吗?

        DataInputStream imgIn=new DataInputStream(socket.getInputStream());
        DataOutputStream imgOut = new DataOutputStream(new FileOutputStream(host+path)); 
        byte[] byteArr=new byte[1024];

        int bytesRead=0,totalBytesRead=0;

        while (totalBytesRead<imageSize ){

            bytesRead=imgIn.read(byteArr,0,1024);
            totalBytesRead+=bytesRead;
            imgOut.write(byteArr,0,bytesRead);
                imgOut.flush();

        }

       /* while ((bytesRead = imgIn.read(byteArr)) > 0)
        {
          imgOut.write(byteArr, 0, bytesRead);
          imgOut.flush();
        }*/


        imgIn.close();
        imgOut.close();

    }

Thanks for any help! 谢谢你的帮助!

I think if that is the requirement : create the webpage locally. 我认为这是否是必要条件:在本地创建网页。

you should not just download the files (htmls, jpegs etc) , you should replicate the directory structure as well, and you would not need to write seperate code to have that work locally. 您不仅应该下载文件(htmls,jpegs等),还应该复制目录结构,并且不需要编写单独的代码即可在本地工作。

hope it helps :-) 希望能帮助到你 :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM