欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 获得网络资源

程序员文章站 2022-05-06 08:10:00
...
java在网络上请求地址,都会用到URL url = new URL(urlStr)来定位资源,
然后根据url获得输入流in = url.openStream();从而可以得到网络资源。

以下是一个完整的程序代码:

package com.zakisoft.tools;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JOptionPane;

public class GetGSInfo {

private static String GOLD_PRICE_URL = "http://www.kitco.cn/cn/live_charts/goldcny.gif";
private static String SILVER_PRICE_URL = "http://www.kitco.cn/cn/live_charts/silvercny.gif";

private static String SAVE_PATH = "D://Glod_Silver//";

private GetGSInfo() {
Date cd = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

String cdstr = df.format(cd);
String glodOutPath = SAVE_PATH + cdstr + "-Glod.gif";
String silverOutPath = SAVE_PATH + cdstr + "-Silver.gif";

getContext(GOLD_PRICE_URL, glodOutPath);
getContext(SILVER_PRICE_URL, silverOutPath);

JOptionPane.showMessageDialog(null, "价格保存完成...");
}

public void getContext(String urlStr, String outPath) {// 获得网络资源并写入指定文件
InputStream in = null;
OutputStream out = null;
try {
// 用streams,存储获得的资源
URL url = new URL(urlStr);
in = url.openStream();
if (outPath == null) {
out = System.out;
} else {
out = new FileOutputStream(outPath);
}
// 用输出流out,输出到指定位置
byte[] buffer = new byte[1024];
int bytes_read;
while ((bytes_read = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes_read);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
} catch (Exception e) {
}
}
}

public static void main(String[] args) {
new GetGSInfo();
}

}

相关标签: Java Swing .net