java 读取本地文件到ByteArrayOutputStream
时间: 2023-11-27 11:40:07 浏览: 287
为了将本地文件读取到ByteArrayOutputStream中,你可以使用FileInputStream来读取文件的字节数据,并将其写入到ByteArrayOutputStream中。下面是一个示例代码:
```java
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class FileToByteArray {
public static void main(String[] args) {
String filePath = "path/to/file.txt";
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (FileInputStream inputStream = new FileInputStream(filePath)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = outputStream.toByteArray(); System.out.println("读取到的字节数组长度:" + data.length);
System.out.println("读取到的字节数组内容:" + Arrays.toString(data));
}
}
```
阅读全文