zoukankan      html  css  js  c++  java
  • 模拟用户上传头像的功能

     

    package com.practice.upload;

    import java.io.*;
    import java.util.Scanner;

    public class UploadFileDemo {
       public static void main(String[] args) throws IOException {
           //需求:模拟用户上传头像的功能,假设所有的用户头像都应该上传到:项目下的lib文件夹中
           File path=getPath();
           System.out.println(path);

           boolean flag=isExists(path.getName());
           //3、如果存在。提示头像已存在,上传失败
           if (flag){
               System.out.println("该用户头像已经存在,上传失败");
               //4、如果不存在,就上传该用户头像,并提示上传成功
          }else{
               //定义方法,用来上传具体的用户头像
               uploadFile(path);
          }

      }
       //1、定义一个方法用来获取要上传的用户头像的路径.方法返回值为File类型的对象
       public static File getPath(){
           //提示用户录入要上传的头像路径,并接收
           Scanner sc=new Scanner(System.in);
           //不知道用户要录入多少次才正确,所以用while循环
           while(true){
               System.out.println("请录入您要上传的用户头像路径:");
               String path=sc.nextLine();
               //判断该路径的后缀名是否是.jpg .png .bmp
               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("您录入的路径不合法,请重新录入");
              }
          }
      }
       //2、定义一个方法用来判断要上传的图片在lib文件夹中是否已经存在
       public static boolean isExists(String path){
           //将lib文件夹封装成File对象
            File file=new File("lib");
           //获取lib文件夹中所有的文件的名称数组
            String[] names=file.list();
           //遍历获取到的数组,用获取到的数据依次和path进行比较
           for (String name:names) {
               if(name.equals(path)){
                   return true;
              }
          }
           return false;
      }
       public static void uploadFile(File path) throws IOException{//path是数据源文件的路径
           InputStream is=new FileInputStream(path);
           OutputStream os=new FileOutputStream("lib/"+path.getName());
           int len;
           while ((len=is.read())!=-1){
               os.write(len);
          }
           is.close();
           os.close();
           System.out.println("上传成功");
      }
    }

     

  • 相关阅读:
    SAP 移动类型 整理
    VB6及VS2005 相关的 树TREE控件,网格控件、电子表格控件、网络图及甘持图控件(项目进度)
    金蝶 PK 用友,第三方评论与自我评价(1)
    谁在开发“工作流”WORKFLOW 产品?
    协同及ERP开发平台,我们如何选择?
    关注“北京广联达软件公司”的项目成本管理系统 !
    一个免费提供的开发平台___"KCOM 商业工程"
    企业 ISO“质量、安全和环境” 三大体系认证的管理系统的开发者 !
    MAXWELL 万胜系统软件公司——为工程建设承包商提供优秀的软件套件!
    Contractor Anywhere (任何地方的承包商)也被 SAGE “赛捷”公司收购 !
  • 原文地址:https://www.cnblogs.com/wyj96/p/11918607.html
Copyright © 2011-2022 走看看