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=