从文件夹中复制图片
从这个文件夹:
复制到这个空的文件夹:
代码如下:
import java.io.*;
import java.util.Scanner;
/**
* 普通文件的复制
*/
public class TestDome10 {
public static void main(String[] args) {
// 输入两个路径
// 从哪里(源路径)拷贝到哪里(目标路径)
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要拷贝源文件的路径:");
String srcPath = scanner.next("G:/photo/sb/kkkk.jpeg");
System.out.println("请输入要拷贝到的目标路径:");
String destPath = scanner.next("G:/Program/xxx/kkkk.jpeg");
File srcFile = new File(srcPath);
if (!srcFile.isFile()) {
//如果不是一个文件(或者是个目录/不存在)
System.out.println("您当前输入的源文件的路径有误!");
return;
}
File destFile = new File(destPath);
if (destFile.isFile()) {
//如果该文件已经存在,也不能进行拷贝
System.out.println("您输入的目标路径有误");
return;
}
//完成拷贝操作
try (InputStream inputStream = new FileInputStream(srcFile);
OutputStream outputStream = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
while (true) {
int b = inputStream.read(buffer);
if (b == -1) {
break;
}
outputStream.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
..........................................................................................................................................................
从网址中复制图片,选择图片:
网址:
小黄鸡表情包 - 高清图片,堆糖,美图壁纸兴趣社区
复制到此文件夹中
代码如下:
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Copy {
public static void main(String[] args) {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try { //输入要复印的网址
URL url = new URL("https://c-ssl.dtstatic.com/uploads/item/202004/09/20200409235851_xwrjt.thumb.1000_0.jpg");
URLConnection urlConnection = url.openConnection();
inputStream = urlConnection.getInputStream();
File file = new File("G:/Program/xxx/kkkk.jpg"); //输入要复印到的目标地址
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) != -1){
outputStream.write(buffer,0,length);
}
}catch (IOException e){
throw new RuntimeException(e);
}finally {
try {
outputStream.close();
}catch (IOException e){
throw new RuntimeException(e);
}try {
inputStream.close();
}catch (IOException e){
throw new RuntimeException(e);
}
}
}
}
运行效果如图: