您的位置:首页 > 编程语言 > Java开发

JAVA中,把电脑里所有的.jpg文件保存到f盘指定目录下,并且文件不重名

2016-03-29 23:18 666 查看
//客户端代码

import java.io.File;

import java.io.FileFilter;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

public class Client3 {

public static void main(String[] args) throws IOException {

File[] roots = File.listRoots();
for (File root : roots) {
getfile(root);
}
// 将d盘中的所有jpg文件都发送到f盘
/*File f=new File("d:");
getfile(f);*/
}
// 判断文件是不是都是以jpg结尾的
public static void getfile(File root) throws IOException {
File[] file = root.listFiles(new FileFilter() {
@Override
//pathname 是路径名字
public boolean accept(File pathname) {
return pathname.isDirectory() || (pathname.isFile() && pathname.getName().endsWith(".jpg"));
}
});
// 先判断java是否有权限进入
if (file != null) {
// 遍历整个文件夹
for (File file2 : file) {
if (file2.isDirectory()) {
getfile(file2);
} else {
sendfile(file2);
}

}
}

}
public static void sendfile(File file2) throws IOException {
// 建立客户端对象
Socket s = new Socket("192.168.1.108", 9090);
// 建立客户端输入流,读取本地文件
FileInputStream in = new FileInputStream(file2);
// 获取客户端输出流
OutputStream out = s.getOutputStream();
// 模版代码读取
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
// 向服务端发送信息
out.write(buf, 0, len);
}
s.shutdownOutput();
// 关闭自己建立的流对象
in.close();
System.out.println("客户端数据读写完毕,正在发往服务端");
///////////////////////////////////////////
// 获取输入流对象
InputStream inp = s.getInputStream();
byte[] buft = new byte[1024];
int length = inp.read(buft);
System.out.println(new String(buft, 0, length));
s.close();
}


}

//服务端代码

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

public class Srever3 {

public static void main(String[] args) throws IOException {
// 获取服务端对象
ServerSocket ss = new ServerSocket(9090);
// 获取客户端对象
while (true) {
final Socket s = ss.accept();
// 获取客户端输入流
InputStream in = s.getInputStream();
// 建立输出流
String ip = s.getInetAddress().getHostAddress();
// 创建输出的文件夹
File file = new File("f:/1/TCP1/" + ip + ".jpg");
int cnt = 0;
// 判断当前这个file对象在硬盘上是否已经存在
while (file.exists()) {
file = new File("f:/1/TCP1/" + ip + "(" + cnt + ")" + ".jpg");
cnt++;
}
FileOutputStream fos = new FileOutputStream(file);
// 模版代码读取文件
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
System.out.println(ip + "正在连接本地服务端");
fos.close();
////////// 服务端接受完毕,返回客户端消息/////////////////////////
OutputStream out = s.getOutputStream();
out.write("文件上传成功,请继续".getBytes());
s.close();
// ss.close();
}
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: