0
我試圖製作一個下載文件的程序。在下載文件時,需要有一個基本的計數器,從頭到尾進行計數。這兩個功能需要在他們自己的線程中。我創建了一個方法/線程來下載文件。我很難弄清楚如何製作一個基本的計數器。沒有什麼奇特的,但它需要計數,只顯示當前的數字。任何幫助,將不勝感激。創建線程下載文件並創建計數器java
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static myutilites.methods.*;
public class Downloader
{
public static void main(String[] args) throws IOException
{
String filename = "Nexus5MahdiRom.zip";
URL link = new URL(
"http://files.mahdi-rom.com/OnePlus%20One/"
+ "OnePlus%20One%20Builds/mahdi-2.7-bacon-20140903.zip");
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
downloadFile(filename,link);
} catch (IOException e)
{
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try {
counter(link, t1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
println("Downloading File...");
}
public void getScreenSize()
{
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
println("width = " + d.width + " height = " + d.height);
}
public static void downloadFile(String fileName, URL link) throws IOException
{
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte [] buf = new byte[1024];
int n = 0;
int count = 0;
while (-1 !=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
println(count);
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
println("Download Finished");
}
public static void locate(int row, int col)
{
System.out.print("\033["+row+";"+col+"H");
}
public static int counter(URL link, Thread t1) throws IOException
{
int count = 0;
link.openConnection();
while(t1.isAlive())
{
count++;
return count;
}
return count;
}
}
我試過這個,但是當我打印到屏幕上它只是保持顯示數字。我想要新號碼刪除舊號碼。我不希望在下載過程中顯示整個計數。只需一個號碼,刪除該號碼,然後刪除下一個號碼。 – user3242607 2014-09-30 02:00:21
@ user3242607在定義'filename'和'link'的相同位置定義AtomicInteger,並將它作爲參數傳遞給'counter'。因爲您通過引用傳遞AtomicInteger,所以將'counter'更改爲'void'方法 – 2014-09-30 02:06:18