Java IO学习笔记+代码(3)
2007-03-20 16:07
711 查看
1、HTTP方式:
/**
* 通过HTTP方式获取文件
*
* @param strUrl
* @param fileName
* @return
* @throws IOException
*/
private boolean getRemoteFile(String strUrl, String fileName) throws IOException {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
DataInputStream input = new DataInputStream(conn.getInputStream());
DataOutputStream output = new DataOutputStream(new FileOutputStream(fileName));
byte[] buffer = new byte[1024 * 8];
int count = 0;
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
output.close();
input.close();
return true;
}
调用时使用下面的数据测试通过,本地得到了test.gif:
String fileUrl = "http://www.google.cn/intl/zh-CN/images/logo_cn.gif";
String fileName = "test.gif";
支持FTP方式的获取,只需要如下改动:
// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
URLConnection conn = url.openConnection();
下面的测试代码也成功执行,本地环境获得了cu_html.zip文件:
public static void main(String[] args) throws IOException {
String fileUrl = "ftp://ftp.cuhk.hk/pub/cu_html.zip";
String fileName = "cu_html.zip";
Test1 test = new Test1();
System.out.println(test.getRemoteFile(fileUrl, fileName));
}
/**
* 通过HTTP方式获取文件
*
* @param strUrl
* @param fileName
* @return
* @throws IOException
*/
private boolean getRemoteFile(String strUrl, String fileName) throws IOException {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
DataInputStream input = new DataInputStream(conn.getInputStream());
DataOutputStream output = new DataOutputStream(new FileOutputStream(fileName));
byte[] buffer = new byte[1024 * 8];
int count = 0;
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
output.close();
input.close();
return true;
}
调用时使用下面的数据测试通过,本地得到了test.gif:
String fileUrl = "http://www.google.cn/intl/zh-CN/images/logo_cn.gif";
String fileName = "test.gif";
支持FTP方式的获取,只需要如下改动:
// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
URLConnection conn = url.openConnection();
下面的测试代码也成功执行,本地环境获得了cu_html.zip文件:
public static void main(String[] args) throws IOException {
String fileUrl = "ftp://ftp.cuhk.hk/pub/cu_html.zip";
String fileName = "cu_html.zip";
Test1 test = new Test1();
System.out.println(test.getRemoteFile(fileUrl, fileName));
}
相关文章推荐
- Java IO学习笔记+代码(3)
- Java IO学习笔记+代码(2)
- Java IO学习笔记+代码(1)
- Java IO学习笔记+代码
- Java IO学习笔记+代码(2)
- Java IO学习笔记+代码(1)
- Java IO学习笔记+代码(2)
- Java IO学习笔记+代码
- DELPHI调用JAVA代码学习笔记1
- [学习笔记]EXCEL导入功能java代码实现
- Java学习笔记之IO
- java学习笔记(四)——io操作
- [Java学习笔记] 容易被忽略的代码
- 12. JAVA IO Part 4 (对象的序列化) ----- 学习笔记
- 【java学习笔记】【特别】Byte输出为二进制字符串的代码
- Android(java)学习笔记113:Android编写代码调用Vibrator震动功能(Bug:按下按钮button始终没有震动)
- Java IO的个人学习笔记(1)
- Java学习笔记之IO(五):BufferedOutputStream缓冲输出字节流
- Java学习笔记之IO(七):FileReader输入字符流
- 【代码笔记】Java学习一阶段总结