java代码转换为python的代码,由于本人不会java,所以求指教,下面是一小段!
privatebooleandownloadFile(StringsURL,StringsName){FilefTile=newFile(sPath+"\\"+sName...
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;
} 展开
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;
} 展开
展开全部
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
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询