什么头像这么难看,去换了它!!!!
有没有想过当你看你的头像十分的不顺眼时,去换头像,这个功能是怎么实现的呢?
模拟在实际开发中上转头像的功能,因为代码不是在真正的开发中,只是通过代码来讲解此功能的实现过程,所以在此代码实现的是把一张图片上传到一个没有这张图片的文件夹中,注意:此代码的图片上传是通过路径来实现的。
代码解析:
一:创建一个方法来判断您要上传的文件是不是一个图片,通过文件的后缀名来判断".jpg","bmp",".png"
二:创建一个方法来判断你上传的文件路径是不是存在,是不是一个文件
三:创建一个方法去实现图片上传功能,就是通过字节缓冲流来进行
四:通过调用来执行上面的三个方法去实现文件的上传
注意:如果不是很懂字节缓冲流等代码可以查看我的其他文章,都有很详细的讲解
package test1;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
public class a1 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
File path_test = path();
System.out.println(path_test);
//System.out.println(path_test.getName());
System.out.println("请输入要传入的文件夹");
Scanner test2 = new Scanner(System.in);
String test3 =test2.nextLine();
System.out.println(test3);
boolean test4 = isexists(path_test.getName(),test3);
System.out.println(test4);
if (test4==true){
System.out.println("文件已存在,图片上传失败");
}
else{
zijie(path_test,test3+path_test.getName());
}
}
public static File path(){
Scanner get_path = new Scanner(System.in);
while(true){
String path = get_path.nextLine();
if (!path.endsWith(".jpg")&& !path.endsWith("bmp") && !path.endsWith(".png") ){
System.out.println("输入的图片出现错误,请重新输入");
}
File test1 = new File(path);
if( test1.exists()&& test1.isFile()){
return test1;
}
else{
System.out.println("图片输入的路径不对,请重新输入");
continue;
}
}
}
//创建一个方法来判断要上传的文件夹中是否有没有这个文件
public static boolean isexists(String file_path,String path_test){
//输入要传入的文件夹
//遍历输出文件夹中的所有内容
File fe1 = new File(path_test);
String [] list = fe1.list();
//通过循环来判断文件是否存在
for(String name:list){
if(name.equals(file_path)){
return true;
}
}return false;
}
public static void zijie(File path_test,String path_two) throws Exception{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path_test));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path_two));
int len;
while((len=bis.read())!=-1){
bos.write(len);
}
bis.close();
bos.close();
}
}
后面会出通过GUI来实现此功能,如果看的有兴趣,就留个关注吧!!
现已更新通过图形化界面来实现功能如果感兴趣https://blog.csdn.net/m0_52479012/article/details/116147594?spm=1001.2014.3001.5501点击即可。