InputStream的长度怎么获取
时间: 2023-07-24 10:30:34 浏览: 148
在Java中,获取InputStream的长度可以通过以下步骤完成:
1. 使用available()方法获取可读取的字节数。
2. 如果available()方法返回的值为0,则需要使用InputStream的read()方法读取一个字节,直到read()方法返回-1为止。
3. 使用mark()方法标记当前位置,然后使用skip()方法跳过所有未读取的字节直到末尾。
4. 使用reset()方法返回到标记的位置。
示例代码如下:
```
InputStream inputStream = new FileInputStream("example.txt");
int length = inputStream.available();
if (length == 0) {
int b = inputStream.read();
while (b != -1) {
length++;
b = inputStream.read();
}
inputStream.close();
} else {
inputStream.mark(length);
inputStream.skip(length);
inputStream.reset();
}
System.out.println("InputStream的长度为:" + length);
```
相关问题
获取InputStream的contentLength长度
获取InputStream的contentLength长度可以使用BufferedInputStream对InputStream进行包装,然后使用available()方法获取可读取的字节数,即为contentLength的长度。代码如下:
```
URL url = new URL("https://example.com/test.txt");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
int contentLength = bufferedInputStream.available();
```
需要注意的是,available()方法并不是总能返回contentLength的长度,因为available()只能返回目前的可读字节数,有可能与contentLength的长度不一致。因此,建议还是使用getContentLength()方法获取contentLength的长度。
InputStream 获取文件大小
InputStream是Java中用于读取数据的抽象类它提供了一系列方法来读不同类型的数据。然而,InputStream并没有直接提供获取文件大小的方法。要获取文件大小,你可以使用File类来获取文件的长度。
以下是获取文件大小步骤:
1. 创建一个File对象,指定要获取大小的文件路径。
2. 调用File对象的length()方法,该方法返回文件的大小,以字节为单位。
示例代码如下:
```java
import java.io.File;
public class FileSizeExample {
public static void main(String[] args) {
File file = new File("path/to/file.txt");
long fileSize = file.length();
System.out.println("File size: " + fileSize + " bytes");
}
}
```
请注意,上述代码中的"path/to/file.txt"应替换为你要获取大小的实际文件路径。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)