import java.io.FileOutputStream;
import java.io.IOException;
public class ByteArrayToFile {
public static void main(String[] args) {
// 定义要写入文件的byte数组
byte[] bytes = "Hello, World!".getBytes();
// 指定文件路径
String filePath = "output.txt";
// 使用FileOutputStream将byte数组写入文件
try (FileOutputStream fos = new FileOutputStream(filePath)) {
fos.write(bytes);
System.out.println("Byte数组已成功写入文件: " + filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
getBytes()
方法会将字符串转换为字节数组。filePath
变量指定了我们要写入的目标文件路径,这里是一个名为 output.txt
的文件。FileOutputStream
类,我们可以将字节数组写入文件。try-with-resources
语句确保了文件流在操作完成后自动关闭,避免资源泄露。IOException
,以确保程序不会因为文件操作失败而崩溃。如果需要更复杂的文件操作或处理更大的数据量,可以考虑使用缓冲区(如 BufferedOutputStream
)或其他高级I/O类。
上一篇:java判断integer为空
下一篇:java代码运行
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站