下载远程文件

	     new Thread(new Runnable()
					{
						public void run()
						{
							String path = urlPath.getText();
							try
							{
								URL url = new URL(path);
								URLConnection conn = url.openConnection();
								InputStream in = conn.getInputStream();

								String saveName = null;
								saveName = url.getPath().substring(
										url.getPath().lastIndexOf("/")+1);
								System.out.println(saveName);
								File saveFile = new File(saveName);
								if (!saveFile.exists())
									saveFile.createNewFile();
								FileOutputStream fos = new FileOutputStream(
										saveFile);

								int fileLen = conn.getContentLength();

								progressBar.setMaximum(fileLen);
								progressBar.setMinimum(0);

								byte[] filebuf = new byte[fileLen];
								byte[] tmpbuf = new byte[1024];
								int readcount = 0;
								int readnum = 0;
								while (readcount < fileLen && readnum != -1)
								{
									readnum = in.read(tmpbuf);

									if (readnum > -1)
									{
										System.arraycopy(tmpbuf, 0, filebuf,
												readcount, readnum);
										readcount += readnum;
									}
									progressBar.setValue(readcount);
								}

								if (readcount < fileLen)
								{
									System.out.println("Download error !");
									// retrun false;
								}
								fos.write(filebuf);
								fos.close();
								in.close();
								System.out.println("Download over !");

							}
							catch (MalformedURLException e1)
							{
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							catch (IOException e1)
							{
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
					}
					).start();

 

你可能感兴趣的:(thread)