天天看點

java模拟使用者上傳頭像(完整)

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("上傳成功,哦吼吼 ");
}
}