1. import java.io.*;:导入 Java 的 io 库,用于文件读写操作
  2. public class one {:定义一个名为 one 的公共类
  3. public static void main(String[] args) {:定义一个名为 main 的公共静态方法,接收字符串数组参数
  4. String filePath = "C:\Users\Administrator\IdeaProjects\untitled\src\test.jpg";:定义一个字符串变量 filePath,用于存储要上传的图片文件路径
  5. try {:开始 try-catch 块
  6. FileInputStream fis = new FileInputStream(filePath);:创建一个文件输入流 fis,用于读取 filePath 所指定的文件
  7. ByteArrayOutputStream baos = new ByteArrayOutputStream();:创建一个字节数组输出流 baos,用于保存从文件输入流读取的数据
  8. byte[] buffer = new byte[1024];:定义一个长度为 1024 的字节数组 buffer,用于存储从文件输入流中读取的数据
  9. int len;:定义一个整型变量 len
  10. while ((len = fis.read(buffer)) != -1) {:当从文件输入流中读取数据到 buffer 数组中时,循环执行以下代码
  11. baos.write(buffer, 0, len);:将从 buffer 数组中读取的数据写入到字节数组输出流 baos 中
  12. fis.close();:关闭文件输入流 fis
  13. baos.close();:关闭字节数组输出流 baos
  14. byte[] imageData = baos.toByteArray();:将字节数组输出流 baos 中的数据转换为字节数组,并保存到 imageData 变量中
  15. String targetFilePath = "C:\Users\Administrator\IdeaProjects\untitled\src\tar\one.jpg";:定义一个字符串变量 targetFilePath,用于存储目标项目中保存图片的路径
  16. BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(imageData));:创建一个缓冲输入流 bis,用于从 imageData 字节数组中读取数据
  17. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFilePath));:创建一个缓冲输出流 bos,用于将数据写入到 targetFilePath 所指定的文件中
  18. byte[] targetBuffer = new byte[1024];:定义一个长度为 1024 的字节数组 targetBuffer,用于存储从 bis 中读取的数据
  19. int targetLen;:定义一个整型变量 targetLen
  20. while ((targetLen = bis.read(targetBuffer)) != -1) {:当从 bis 中读取数据到 targetBuffer 数组中时,循环执行以下代码
  21. bos.write(targetBuffer, 0, targetLen);:将从 targetBuffer 数组中读取的数据写入到缓冲输出流 bos 中
  22. bis.close();:关闭缓冲输入流 bis
  23. bos.close();:关闭缓冲输出流 bos
  24. System.out.println("图片上传成功!");:打印字符串 "图片上传成功!"
  25. } catch (IOException e) {:捕获可能出现的 IOException 异常
  26. e.printStackTrace();:打印异常堆栈信息
  27. }:结束 try-catch
import javaio;public class one public static void mainString args String filePath = CUsersAdministratorIdeaProjectsuntitledsrctestjpg; 要上传的图片文件路径 try FileInputStream fi

原文地址: https://www.cveoy.top/t/topic/fqZL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录