java网络编程-下载二进制文件的正确流写法

从服务器下载二进制文件时,HTTP服务器并不总是会在数据发送完后就立即关闭连接,因此,你不知何时停止读取。所以需要改进一下网络流读取的算法。

public void saveBinaryFile(URL u) throws IOException {
		URLConnection uc = u.openConnection();
		String contentType = uc.getContentType();
		int contentLength = uc.getContentLength();
		if (contentType.startsWith("text/") || contentLength == -1) {
			throw new IOException("This is not a binary file.");
		}
		try (InputStream raw = uc.getInputStream()) {
			InputStream in = new BufferedInputStream(raw);
			byte[] data = new byte[contentLength];
			int offset = 0;
			while (offset < contentLength) {
				int bytesRead = in.read(data, offset, data.length - offset);
				if (bytesRead == -1) {
					break;
				}
				offset += bytesRead;
			}
			if (offset != contentLength) {
				throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes.");
			}
			String fileName = u.getFile();
			fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
			try (FileOutputStream fout = new FileOutputStream(fileName)) {
				fout.write(data);
				fout.flush();
			}
		}
	}


猜你喜欢

转载自blog.csdn.net/cgs666/article/details/51171033