import javaio;public class one public static void mainString args String filePath = CUsersAdministratorIdeaProjectsuntitledsrctestjpg; 要上传的图片文件路径 try FileInputStream fi
- import java.io.*;:导入 Java 的 io 库,用于文件读写操作
- public class one {:定义一个名为 one 的公共类
- public static void main(String[] args) {:定义一个名为 main 的公共静态方法,接收字符串数组参数
- String filePath = "C:\Users\Administrator\IdeaProjects\untitled\src\test.jpg";:定义一个字符串变量 filePath,用于存储要上传的图片文件路径
- try {:开始 try-catch 块
- FileInputStream fis = new FileInputStream(filePath);:创建一个文件输入流 fis,用于读取 filePath 所指定的文件
- ByteArrayOutputStream baos = new ByteArrayOutputStream();:创建一个字节数组输出流 baos,用于保存从文件输入流读取的数据
- byte[] buffer = new byte[1024];:定义一个长度为 1024 的字节数组 buffer,用于存储从文件输入流中读取的数据
- int len;:定义一个整型变量 len
- while ((len = fis.read(buffer)) != -1) {:当从文件输入流中读取数据到 buffer 数组中时,循环执行以下代码
- baos.write(buffer, 0, len);:将从 buffer 数组中读取的数据写入到字节数组输出流 baos 中
- fis.close();:关闭文件输入流 fis
- baos.close();:关闭字节数组输出流 baos
- byte[] imageData = baos.toByteArray();:将字节数组输出流 baos 中的数据转换为字节数组,并保存到 imageData 变量中
- String targetFilePath = "C:\Users\Administrator\IdeaProjects\untitled\src\tar\one.jpg";:定义一个字符串变量 targetFilePath,用于存储目标项目中保存图片的路径
- BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(imageData));:创建一个缓冲输入流 bis,用于从 imageData 字节数组中读取数据
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFilePath));:创建一个缓冲输出流 bos,用于将数据写入到 targetFilePath 所指定的文件中
- byte[] targetBuffer = new byte[1024];:定义一个长度为 1024 的字节数组 targetBuffer,用于存储从 bis 中读取的数据
- int targetLen;:定义一个整型变量 targetLen
- while ((targetLen = bis.read(targetBuffer)) != -1) {:当从 bis 中读取数据到 targetBuffer 数组中时,循环执行以下代码
- bos.write(targetBuffer, 0, targetLen);:将从 targetBuffer 数组中读取的数据写入到缓冲输出流 bos 中
- bis.close();:关闭缓冲输入流 bis
- bos.close();:关闭缓冲输出流 bos
- System.out.println("图片上传成功!");:打印字符串 "图片上传成功!"
- } catch (IOException e) {:捕获可能出现的 IOException 异常
- e.printStackTrace();:打印异常堆栈信息
- }:结束 try-catch
原文地址: https://www.cveoy.top/t/topic/fqZL 著作权归作者所有。请勿转载和采集!