拷贝局域网共享文件
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class ImageDownloader {
public static void main(String[] args) {
String targetIp = "192.168.10.249"; // 替换为目标IP地址192.168.10.2
String targetFolder = "/Users/Public/Pictures/"; // 替换为目标电脑文件夹目录
String localDestination = "C:/Users/31888/Desktop/cese"; // 替换为本地保存目录
List<String> imageUrls = getImageUrlsFromTarget(targetIp, targetFolder);
downloadImages(imageUrls, localDestination);
}
private static List<String> getImageUrlsFromTarget(String targetIp, String targetFolder) {
List<String> imageUrls = new ArrayList<>();
// 构建目标文件夹的URL
String targetUrl = "file://" + targetIp + "/" + targetFolder;
try {
URL url = new URL(targetUrl);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
imageUrls.add(targetUrl + line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageUrls;
}
private static void downloadImages(List<String> imageUrls, String localDestination) {
try {
for (String imageUrl : imageUrls) {
String fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
URL url = new URL(imageUrl);
InputStream inputStream = url.openStream();
OutputStream outputStream = new FileOutputStream(localDestination + "/" + fileName);
byte[] buffer = new byte[2048];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
System.out.println("图片下载完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
查看文件夹里图片全路径加名称方便页面显示图片
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ReadImageNamesWithPath {
public static void main(String[] args) {
// String targetDirectory = "\\\\192.168.10.24\\test\\images";
String targetDirectory = "C:\\Users\\31888\\Desktop\\qwe";
File directory = new File(targetDirectory);
if (!directory.exists() || !directory.isDirectory()) {
System.out.println("无效的目标目录");
return;
}
File[] files = directory.listFiles();
if (files == null || files.length == 0) {
System.out.println("无文件");
return;
}
List<String> list=new ArrayList<>();
for (File file : files) {
if (file.isFile()) {
String name = file.getName().substring(file.getName().lastIndexOf('.') + 1);
if (name.equals("jpg") || name.equals("png")) {
System.out.println("图片名称:"+name);
list.add(file.getAbsolutePath());
}
}
}
System.out.println(list.toString());
}
}