代码: 2进制 读/写

String url = "http://roserouge.iteye.com";
InputStream in = null;
DataOutputStream out = null;
try {
	in = new URL(url).openConnection().getInputStream();
	out = new DataOutputStream(new FileOutputStream(saveAs));
	byte[] b = new byte[1];
	while (-1 != in.read(b))
		out.writeByte((int) b[0]);
} catch (MalformedURLException e) {
	log.error("", e);
} catch (FileNotFoundException e) {
	log.error("", e);
} catch (IOException e) {
	log.error("", e);
} finally {
	try {
		if (null != out)
			out.close();
		if (null != in)
			in.close();
	} catch (IOException e) {
		log.error("", e);
	}
}  
DataInputStream in = null;
DataOutputStream out = null;
try {
	in = new DataInputStream(new URL(url).openConnection().getInputStream());
	out = new DataOutputStream(new FileOutputStream(saveAs));
	while (true)
		out.writeByte(in.readUnsignedByte());
} catch (MalformedURLException e) {
	log.error("", e);
} catch (EOFException e) {
	if (log.isDebugEnabled())
		log.debug(url + " > OK");
} catch (FileNotFoundException e) {
	log.error("", e);
} catch (IOException e) {
	log.error("", e);
} finally {
	try {
		if (null != out)
			out.close();
		if (null != in)
			in.close();
	} catch (IOException e) {
		log.error("", e);
	}
}

 

两段代码效果一样

InputStream.read()  结束时返回 -1

DataInputStream.readUnsignedByte() 结束时抛出 EOFException异常

 

你可能感兴趣的:(代码)