我正在开发一个黑莓应用,我从网络服务获得了一个pdf-url。我需要使用该URL下载该PDF并将其保存到我的SD卡中。
请告诉我,是否有可能。
答案 0 :(得分:0)
我很抱歉回复很晚,我在这项任务中取得了成功。我知道这不是一项“努力工作”,但对我来说这是一个教训。我使用以下线程代码完成此任务。
private class DownloadCombiner extends Thread {
private String remoteName;
private String localName;
private int connection;
private int chunksize;
public DownloadCombiner(String remoteName,
String localName, int connection, int chunksize) {
this.remoteName = remoteName;
this.localName = localName;
this.connection = connection;
this.chunksize = chunksize;
}
public void run() {
try {
int chunkIndex = 0;
int totalSize = 0;
/*
* File connection
*/
FileConnection file =(FileConnection)Connector.open(localName);
if (!file.exists()) {
file.create();
}
file.setWritable(true);
OutputStream out = file.openOutputStream();
/*
* HTTP Connections
*/
String currentFile = remoteName + connectionType();
//log("Full URL: " + currentFile);
HttpConnection conn;
InputStream in;
int rangeStart = 0;
int rangeEnd = 0;
while (true) {
// log("Opening Chunk: " + chunkIndex);
conn = (HttpConnection) Connector.open(currentFile,
Connector.READ_WRITE, true);
rangeStart = chunkIndex * chunksize;
rangeEnd = rangeStart + chunksize - 1;
// log("Requesting Range: " + rangeStart +
// "-" + rangeEnd);
conn.setRequestProperty("Range", "bytes=" +
rangeStart + "-" + rangeEnd);
int responseCode = conn.getResponseCode();
if (responseCode != 200 && responseCode != 206)
{
// log("Response Code = " + conn.getResponseCode());
break;
}
// log("Retreived Range: " + conn.getHeaderField("Content-Range"));
in = conn.openInputStream();
int length = -1;
byte[] readBlock = new byte[256];
int fileSize = 0;
while ((length = in.read(readBlock)) != -1) {
out.write(readBlock, 0, length);
fileSize += length;
Thread.yield(); // Try not to get cut off
}
totalSize += fileSize;
// log("Chunk Downloaded: " + fileSize + " Bytes");
chunkIndex++; // index (range) increase
in.close();
conn.close();
in = null;
conn = null;
/*
* Pause to allow connections to close and other Threads
* to run.
*/
Thread.sleep(1000);
}
// log("Full file downloaded: " + totalSize + " Bytes");
out.close();
file.close();
// log("Wrote file to local storage");
} catch (Exception e) {
System.out.println(e.toString());
}
}
private String connectionType() {
switch (connection) {
case 1:
return ";deviceside=false";
case 2:
return ";deviceside=true;interface=wifi";
default:
return ";deviceside=true";
}
}
}