import java.io.*;
import java.util.Scanner;
public class UploadImg {
public static void main(String[] args) throws IOException {
File file = getPath();
System.out.println(file);
String fileName = file.getName();
if(isExists(fileName)){
System.out.println("文件已存在,上传失败");
}else{
System.out.println("开始上传头像");
uploadFile(file);
}
}
public static File getPath(){
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("请录入要上传的路径");
String path = sc.next();
if(!path.endsWith(".bmp") && !path.endsWith(".jpg") && !path.endsWith(".png")){
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 fileName){
File file = new File("lib");
String[] names = file.list();
for (String name : names) {
if(name.equals(fileName)){
return true;
}
}
return false;
}
public static void uploadFile(File path) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("lib/" + path.getName()));
int data;
while((data = bis.read()) != -1){
bos.write(data);
}
bis.close();
bos.close();
}
}