java模拟用户上传头像(完整)

tech2026-10-05  1

package susu.it; import java.io.*; import java.util.Scanner; //一 。 定义一个方法,用来判断要上传的用户头像的路径 public class UploadFile { public static void main(String[] args) throws IOException { //输入头像路径 File path = getPath(); System.out.println(path); // 头像是否存在在lib中 boolean flag = isExists(path.getName()); // //循环判断头像是否纯在 if (flag) { System.out.println("该用户头像已经存在,不用上传了"); } else { uoloadFile(path ); } } //二 , 定义一个方法, 同来判断用户上传的头像,在lib中是否存在 。 public static File getPath (){ //1 提示用户录入,要传头像的路径 Scanner sc = new Scanner(System.in ); while (true) { System.out.println("请例如要上传头像的路径"); String path = sc.nextLine(); // 2 判断该路径的后缀名是否是 .JPG .png .bmp // 3 如果不是就提示重新录入。 if (!path.endsWith(".JPG") && !path.endsWith(".png") && !path.endsWith(".bmp")) { System.out.println("您录入的不是图片,请重新录入"); continue; } // 如果是,程序继续进行,判断路径是否存在。并且是否是文件 File file = new File(path); if (file.exists() && file.isFile()) { return file; } else System.out.println("您录入的路径不合法,请重新录入"); } } // public static boolean isExists (String path ){ File file = new File("lib"); String[] names = file.list(); for (String name :names ){ if (name.equals(path)){ return true ; } } return false; } //定义方法 : 上传具体的用户头像 // path 数据的源文件 public static void uoloadFile (File path ) throws IOException { //输入流文件 BufferedInputStream bis = new BufferedInputStream( new FileInputStream(path )); //输出流文件 BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream("lib/"+path.getName())); //定义变量 int len ; //循环获取 while ((len = bis.read())!=-1){ //拷贝复制 bos.write(len); } bis.close(); bos.close(); System.out.println("上传成功,哦吼吼 "); } }
最新回复(0)