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())!=-