java 下载http格式的文件

/**
	 * 采用post方式向服务器发起申请
	 * 
	 * @param serviceURL
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public boolean doPost(String serviceURL) throws Exception {
		HttpURLConnection conn = null;
		InputStream inStream = null;
		boolean rst = false;
		URL url = new URL(serviceURL);
		conn = (HttpURLConnection) url.openConnection();
		conn.setDoInput(true);
		inStream = conn.getInputStream();
		
		BufferedInputStream in = new BufferedInputStream(inStream);
		File file = new File("e:\\lmz.mp3");
		if (file != null) {
			file.createNewFile();
		}
		// 指定要写入文件的缓冲输出字节流
		BufferedOutputStream out = new BufferedOutputStream(
				new FileOutputStream(file));
		byte[] bb = new byte[1024];// 用来存储每次读取到的字节数组
		int n;// 每次读取到的字节数组的长度
		while ((n = in.read(bb)) != -1) {
			out.write(bb, 0, n);// 写入到输出流
		}
		out.close();// 关闭流
		in.close();
		System.out.println("拷贝成功");
		inStream.close();
		inStream = null;
		conn.disconnect();
		return rst;
	}

 

 

以上是例子,只要传入一个URL就行了,比如:

 

http://localhost:8080/a/qqmusic.wav,经过上述操作,会在e盘根目录下生成一个lmz.mp3.

 

 

 

流来读写文件

 refurl:http://blog.csdn.net/a107494639/article/details/7586689

 

 

 

 

你可能感兴趣的:(java)