import java.io.*;
/**
* 读取文件生成字节码
*/
public class FileUtils {
public static byte[] toByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int n = 0;
while (-1 != (n = inputStream.read(buffer))){
outputStream.write(buffer,0,n);
}
return outputStream.toByteArray();
}
public static void fileToBytes(byte[] bytes, String filePath, String fileName) throws IOException {
File file = new File(filePath + fileName);
//路径前面的文件夹不存在则会创建文件夹
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try (
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
bos.write(bytes);
}
}
public static void main(String[] args) throws IOException {
File file = new File("/Users/ha/code/test/target/classes/s/Create.class");
try(
InputStream inputStream = new FileInputStream(file);
){
byte[] bytes = toByteArray(inputStream);
fileToBytes(bytes,"/Users/ha/code/test/testtarget/classes/","Create.class");
}
}
}
java文件转换成字节
最新推荐文章于 2024-06-20 18:00:24 发布