import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ByteArrayOutputStream; public class FileToByteArray { public static void main(String[] args) { File file = new File("path/to/your/file.txt"); // 替换为你的文件路径 try { byte[] fileBytes...
打开文件输入流,读取文件内容; 将文件内容写入到一个byte数组中; 关闭文件输入流。 下面将通过一个示例来演示如何实现这一功能。 代码示例 importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;publicclassFileToByteArray{publicstaticbyte[]readFileToByteArray(StringfilePath){byte[]fileBy...
importjava.io.File;importjava.io.IOException;importjava.nio.file.Files;publicclassFileToByteArray{publicstaticvoidmain(String[]args){Filefile=newFile("example.txt");byte[]fileBytes=null;try{// 将文件转换为字节数组fileBytes=Files.readAllBytes(file.toPath());System.out.println("文件成功转换为字节...
byte[] bytes = Files.readAllBytes(Paths.get("C:\\Users\\Marydon\\Desktop\\个人信用报告.pdf")); // 方式二 // bytes = Files.readAllBytes(new File(("C:\\Users\\Marydon\\Desktop\\个人信用报告.pdf")).toPath()); System.out.println(Arrays.toString(bytes)); } catch (IOException e) ...
public static byte[] toByteArray(String filename) throws IOException { File f = new File(filename); if (!f.exists()) { throw new FileNotFoundException(filename); } ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length()); ...
你可以使用Java中的FileInputStream类来读取文件内容到byte数组。 下面是一个示例代码: import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ReadFileToByteArray { public static void main(String[] args) { File file = new File("path/to/file"); // 替换...
fis.read(xml);//现在file中的内容全读到了byte[]数组中 //如果文件中是文本信息那么: String str=new String(xml,"utf-8");就可以得到文字内容 } } } catch (Exception e) {} 反过来,由byte[]转成file也是一样啊,不过FileInputStream 要改成FileOutputStream就可以了,另外read()改成...
buffer = bos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; } /** * 根据byte数组,生成文件 */ public static void getFile(byte[] bfile, String filePath,String fileName) { ...
buffer = bos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; } /** * 根据byte数组,生成文件 */ public static void getFile(byte[] bfile, String filePath,String fileName) { ...
importjava.io.*;publicclassFileToByteStream{publicstaticvoidmain(String[]args){try{Filefile=newFile("example.txt");FileInputStreamfis=newFileInputStream(file);ByteArrayOutputStreambos=newByteArrayOutputStream();byte[]buffer=newbyte[1024];intlength=0;while((length=fis.read(buffer))!=-1){bos.wr...