永发信息网

java代码转换为python的代码,由于本人不会java,所以求指教,下面是一小段!

答案:1  悬赏:20  手机版
解决时间 2021-03-03 00:44
  • 提问者网友:战皆罪
  • 2021-03-02 08:56
private boolean downloadFile(String sURL, String sName) {
File fTile = new File(sPath + "\\" + sName);
if (fTile.exists()) {
return true;
}

int nStartPos = 0;
int nRead = 0;
try {
URL url = new URL(sURL);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
// int state = httpConnection.getResponseCode();
// if(state != 200)
// return false;

long nEndPos = getFileSize(sURL);
if (nEndPos < 0 || nEndPos == 2407)
return false;

RandomAccessFile oSavedFile = new RandomAccessFile(sPath + "\\" + sName, "rw");
httpConnection.setRequestProperty("User-Agent", "Internet Explorer");
String sProperty = "bytes=" + nStartPos + "-";
httpConnection.setRequestProperty("RANGE", sProperty);
InputStream input = httpConnection.getInputStream();
byte[] b = new byte[1024];
while ((nRead = input.read(b, 0, 1024)) > 0 && nStartPos < nEndPos) {
oSavedFile.write(b, 0, nRead);
nStartPos += nRead;
}
oSavedFile.close();
httpConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
最佳答案
  • 五星知识达人网友:鸠书
  • 2021-03-02 09:38
def downloadFile(self,sURL,sName):
        import os.path
        if os.path.exists(os.path.join(self.sPath,sName )):
            return True
        nEndPos=self.getFileSize(sURL)
        if nEndPos<0 or nEndPos == 2407:
            return False
try:
import urllib2
req = urllib2.Request(sURL)
req.add_header("User-Agent", "Internet Explorer")
req.add_header("RANGE","bytes=" + str(0)+ "-")
res = urllib2.urlopen(req)
with open(os.path.join(self.sPath,sName ),'wb') as f:
while True:
data = res.read(1024)
if not data:
break
f.write(data)
res.close()
except Exception as e:
print e
return False
return True
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯