1 package cn.itcast.demo3;
2
3 import java.io.*;
4 import java.util.Scanner;
5
6 public class Test1 {
7 public static void main(String[] args) throws IOException {
8 // 需求:模拟用户上传头像的功能,假设所有的用户的头像都上传到lib目录下
9 // 1. 定义一个方法,用来获取上传头像的路径 getPath()
10 File path = getPath();
11 System.out.println(path);
12
13 // 2. 定义一个方法,用来判断用户上传的头像在 lib 目录下是否存在
14 boolean flag = isExists(path.getName());
15 if (flag) {
16 // 3. 如果存在,提示:该用户头像已存在,上传失败
17 System.out.println("该用户头像已存在,上传失败");
18 }
19 else {
20 // 4. 如果不存在,就上传该用户头像,并提示上传成功
21 uploadFile(path);
22 }
23
24
25
26
27 }
28
29 public static File getPath(){
30 // 1. 提示用户录入 要上传的头像的路径,并接受
31 Scanner sc = new Scanner(System.in);
32
33 // 7. 用while
34 while (true){
35 System.out.println("请录入您要上传的用户头像的路径:");
36 String path = sc.nextLine();
37 // 2. 判断该路径的后缀名 是否为:.jpg .png .bmp
38 // 3. 如果不是,就提示:您录入的不是图片,请重新录入
39 if (!path.endsWith(".jpg") && !path.endsWith(".png") && !path.endsWith(".bmp")){
40 System.out.println("您输入的不是图片,请重新录入:");
41 continue;
42 }
43
44 // 4. 如果存在,程序接着执行,判断文件路径是否存在,并是否为文件
45 File file = new File(path);
46 if (file.exists() && file.isFile()){
47 // 5. 如果是,就说明是我们要的数据,就返回
48 return file;
49 }
50 else{
51 // 6. 如果不是,就提示:您录入的文件路径不存在,请重新录入
52 System.out.println("您录入的路径不合法,请重新录入:");
53 }
54
55
56 }
57
58
59
60
61
62
63 }
64
65 public static boolean isExists(String path){
66 File file = new File("lib");
67
68 String[] names = file.list();
69
70 for (String name : names) {
71 if (name.equals(path)){
72 return true;
73 }
74 }
75
76 return false;
77 }
78
79 // 上传具体用户的头像
80 public static void uploadFile(File path) throws IOException {
81 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
82 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("lib\\" + path.getName()));
83
84 int len;
85 while ((len = bis.read()) != -1){
86 bos.write(len);
87 }
88
89 bis.close();
90 bos.close();
91
92 System.out.println("上传成功!");
93
94 }
95
96
97 }