java读取文件内容输出为Byte[]
时间: 2024-06-12 18:09:59 浏览: 18
可以使用Java的FileInputStream类来读取文件内容,并将其存储为Byte数组。以下是示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileToByteArray {
public static void main(String[] args) {
File file = new File("example.txt"); byte[] fileContent = new byte[(int) file.length()];
try (FileInputStream inputStream = new FileInputStream(file)) {
inputStream.read(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("File content in bytes is: ");
for (int i = 0; i < fileContent.length; i++) {
System.out.print(fileContent[i] + " ");
}
}
}
```
在上面的代码中,我们首先创建一个File对象,该对象引用要读取的文件。然后,我们使用FileInputStream类创建一个输入流,并使用该流读取文件内容。最后,我们将文件内容存储在一个Byte数组中,并将其打印出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)