Java 读取网络资源文件 获取文件大小
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java 读取网络资源文件 获取文件大小,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2451字,纯文字阅读大概需要4分钟。
内容图文
![Java 读取网络资源文件 获取文件大小](/upload/InfoBanner/zyjiaocheng/689/35f00d388f524ff0893538c75a221ff9.jpg)
Java 读取网络资源文件 获取文件大小
封装一个文件操作工具类:
package c;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* @author Jayvee
* @Description: todo 文件操作
*/
public class FileUtils {
/**
* @author Jayvee
* @Description: todo 获取网络文件的大小
*/
public static int getFileLength(String url1) throws IOException {
int length = 0;
URL url;
try {
url = new URL(url1);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
//根据响应获取文件大小
length = urlcon.getContentLength();
urlcon.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return length;
}
/**
* 从输入流中获取字节数组
* @author Jayvee
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
/**
* @author Jayvee
* @Description: todo
*/
public static byte[] downLoadFromUrl(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);
return getData;
}
/**
* @author Jayvee
* @Description: todo
*/
public static byte[] readFromByteFile(String pathname) throws IOException {
File filename = new File(pathname);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
in.close();
byte[] content = out.toByteArray();
return content;
}
}
假设获取网络图片 http://pic.962.net/up/2018-1/2018191570320420.jpg 的大小和内容。
Java 代码:
try {
int fileSize = FileUtils.getFileLength("http://pic.962.net/up/2018-1/2018191570320420.jpg"); // 获取文件大小
byte[] file = FileUtils.downLoadFromUrl("http://pic.962.net/up/2018-1/2018191570320420.jpg"); // 获取文件内容
System.out.println("文件大小:" + fileSize + " 字节");
System.out.println("文件内容:" + file);
} catch (IOException e) {
e.printStackTrace();
}
执行结果:
文件大小:4979 字节
文件内容:[B@7dc5e7b4
内容总结
以上是互联网集市为您收集整理的Java 读取网络资源文件 获取文件大小全部内容,希望文章能够帮你解决Java 读取网络资源文件 获取文件大小所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。