下载的jar文件已损坏

时间:2013-06-30 21:51:06

标签: java url download corrupt

我有这个代码从特定的URL下载.jar文件并将其放入特定的文件夹中。下载的jar文件是游戏的mod,这意味着它必须下载并正确运行而不会被破坏。

问题是,每次我尝试下载文件时,它最终都会以某种方式被破坏并在加载时导致错误。

这是我的下载代码:

final static int size=1024;

public static void downloadFile(String fAddress, String localFileName, String destinationDir, String modID) {
    OutputStream outStream = null;
    URLConnection  uCon = null;

    InputStream is = null;
    try {
        URL Url;
        byte[] buf;
        int ByteRead,ByteWritten=0;
        Url= new URL(fAddress);
        outStream = new BufferedOutputStream(new
                FileOutputStream(destinationDir+"/"+localFileName));

        uCon = Url.openConnection();
        is = uCon.getInputStream();
        buf = new byte[size];
        while ((ByteRead = is.read(buf)) != -1) {
            outStream.write(buf, 0, ByteRead);
            ByteWritten += ByteRead;
        }
        System.out.println("Downloaded Successfully.");
        System.out.println("File name:\""+localFileName+ "\"\nNo ofbytes :" + ByteWritten);
        System.out.println("Writing info file");
        WriteInfo.createInfoFile(localFileName, modID);
    }catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        try {
            is.close();
            outStream.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

任何想法这个代码有什么问题?

2 个答案:

答案 0 :(得分:0)

不确定这是否能解决您的问题,但最后应该冲洗缓冲区。

outStream.flush();

答案 1 :(得分:0)

你的代码看起来很正确;试试这个

public static void downloadFromUrl(String srcAddress, String userAgent, String destDir, String destFileName, boolean overwrite) throws Exception
   {
      InputStream is = null;
      FileOutputStream fos = null;

      try
      {
         File destFile = new File(destDir, destFileName);
         if(overwrite && destFile.exists())
         {
            boolean deleted = destFile.delete();
            if (!deleted)
            {
               throw new Exception(String.format("d'ho, an immortal file %s", destFile.getAbsolutePath()));
            }
         }

         URL url = new URL(srcAddress);
         URLConnection urlConnection = url.openConnection();

         if(userAgent != null)
         {
            urlConnection.setRequestProperty("User-Agent", userAgent);
         }

         is = urlConnection.getInputStream();
         fos = new FileOutputStream(destFile);

         byte[] buffer = new byte[4096];

         int len, totBytes = 0;
         while((len = is.read(buffer)) > 0)
         {
            totBytes += len;
            fos.write(buffer, 0, len);
         }

         System.out.println("Downloaded successfully");
         System.out.println(String.format("File name: %s - No of bytes: %,d", destFile.getAbsolutePath(), totBytes));
      }
      finally
      {
         try
         {
            if(is != null) is.close();
         }
         finally
         {
            if(fos != null) fos.close();
         }
      }
   }