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("上传成功");
      }
    }

     

  • 相关阅读:
    Windows Server 2003 SP2(32位) 中文版 下载地址 光盘整合方法
    用Recycle()方法对Java对象的重要性
    Lotus中千奇百怪的 $$
    Developing a simple application using steps "User Decision" and "Mail"(1) 沧海
    沟通中的情绪管理(演讲稿) 沧海
    人只有在压力之下,才可能成功,没做一件事,都必须成功,不许言败 沧海
    什么是IDOC,以及IDOC的步骤 沧海
    VS2008 Professional Edition CHS中的deffactory.dat读取错误 沧海
    Including custom text in the step "User Decision" 沧海
    SAP Upgrade Strategy 沧海
  • 原文地址:https://www.cnblogs.com/wyj96/p/11918607.html
Copyright © 2011-2022 走看看