public class Download { // 主线程下载
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException { // 主函数
String path = new String(http://192.168.1.122/haha/GEM.mp3); // 下载的资源的地址,这里用的是tomcat开启的本地服务器。
new Download().Downloadmp3(path); // 将资源地址传入,写一个Downloadmp3(Sting path)方法。
}
private void Downloadmp3(String path) throws IOException {
URL url = new URL(path); // 新建一个URL对象,通过URL中的openConnection()方法得到资源连接对象。
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000); // 设置连接超时
conn.setRequestMethod("GET"); // 提交方式为GET
int Length=conn.getContentLength(); // 得到资源长度
if(conn.getResponseCode()==200){ // if连接成功
InputStream input = conn.getInputStream(); // 资源输入流
File file=new File("GEM.mp3"); // 新建名为GEM.mp3文件,默认地址工程目录
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
accessFile.setLength(Length); //文件长度
FileOutputStream output = new FileOutputStream(file); //新建该文件输出流
int flog = 0;
byte[] buffer = new byte[4*1024];
while ((flog=input.read(buffer)) != -1) { //输入流不为空则将内容写入文件
accessFile.write(buffer, 0, flog);
}
output.flush();
input.close(); //关闭输入流
}
else {
System.out.println("下载失败!");
}
}
}