java - 从InputStream获取URL

标签 java stream java-io

我想知道java中的InputStream是如何从底层角度实现的。

假设我编写了下面的 java 代码来与网站建立连接。

url = new URL("[some url info]");
URLConnection urlcon = url.openConnection();
InputStream in = urlcon.getInputStream();
while((readcount = in.read(buffer)) != -1){
        fos.write(buffer,0,readcount);

我可以通过转换它的类型直接从InputStream(上面代码块中的“in”)知道URL并调用如下所示的适当方法吗?还有其他方法可以从InputStream获取URL吗?

(newtype) new = (newtype) in;
String Url = new.appropriatemethod();

我搜索了InputStream的所有子类,但找不到任何具有提供其URL的接口(interface)的类。 (https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html)

但是,我认为 InputStream 某种程度上具有 URL 信息,可以从具有该 URL 的网站接收数据。

我可能对“Stream”有很大的误解。

感谢您阅读我的问题。 :)

最佳答案

InputStream 只是一个 stream不是 URLConnection。当您输入 InputStream in = urlcon.getInputStream(); 时。您将获得输入流而不是 url 连接。当您输入 in.read 时,您正在读取 Stream,而不是 URLConnection

An InputStream is a reference to source of data (be it a file, network connection etc), that we want to process as follows:

  • we generally want to read the data as "raw bytes" and then write our own code to do something interesting with the bytes;

  • we generally want to read the data in sequential order: that is, to get to the nth byte of data, we have to read all the preceding bytes first, and we're not guaranteed to be able to "jump back" again once we've read them.

关于java - 从InputStream获取URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42592310/

相关文章:

c# - 我如何预先设置流?

java - 存储在字符串中

java - 检查文件是否存在并且在java中可读的最佳方法

java - 使用 Java 程序将 String 转换为 jena 中的模型或语句?

java - 无法chmod文件夹写入

java - 无法设置 JFrame 的最大大小(Windows 下)

java - 如何将 Stream 转换为 Int?

javascript - 如何让 NodeJS Transform 流为每个输入 block 发出多个记录?

java.io.IOException : Stream closed at java. util.zip.ZipInputStream.ensureOpen(ZipInputStream.java:66)

java - Android效果波纹圆圈imageView