###文件传输小工具
public class FileCopyUtils {
/**
* 将一个源file对象拷贝到另一个目标file
* @param source 源文件(可能是目录)
* @param target 目标目录
* @throws IOException
*/
public static void copy(File source,File targetDir) throws IOException{
//判断当前需要被拷贝对象是目录还是标准文件
if(source.isDirectory()){
//在目录中创建子目录(不存在)
targetDir = new File(targetDir,source.getName());
if(!targetDir.exists()){
//如果目录不存在则试图创建
if(!targetDir.mkdirs()){
throw new FileNotFoundException("目录创建失败,请检查权限");
}
}
//读取目录
File[] files = source.listFiles();
if(Objects.nonNull(files)){
for (int i = 0; i < files.length; i++) {
copy(files[i],targetDir);
}
}
}else{
//文件拷贝
copyFile(source,targetDir);
}
}
private static void copyFile(File source, File targetDir) throws IOException {
BufferedInputStream bis = null;
BufferedOutputStream bow = null;
try{
//获取源文件的输入流并包装为缓冲流
bis = new BufferedInputStream(new FileInputStream(source));
//根据源文件文件名组合目标目录成为新文件对象
File target = new File(targetDir,source.getName());
//获取目标文件的输出流
bow = new BufferedOutputStream(new FileOutputStream(target));
//声明字节缓冲区,缓存读取的字节数据
byte[] b = new byte[1024];
int len = 0;
//循环读写
while((len = bis.read(b)) != -1){
bow.write(b, 0, len);
}
}finally{
//关闭资源
if(bow != null)bow.close();
if(bis != null)bis.close();
}
}
}
联系socket实现网络传输
###发送端(服务器)
public class Server {
public static void main(String[] args) throws IOException {
// 创建服务器,使用端口(8888)
ServerSocket server = new ServerSocket(8888);
System.out.println("服务已创建,等待连接...");
// 循环监听
while (true) {
// 开始监听,一旦客户端连接则返回Socket对象
Socket s = server.accept();
System.out.println("客户端已连接!" + s.getInetAddress());
// 获取Socket的输出流
OutputStream os = s.getOutputStream();
File source = new File("F:\\Note\\贫穷.jpg");
// 获取文件输入流
FileInputStream fis = new FileInputStream(source);
// 获取文件缓冲流
BufferedOutputStream bos = new BufferedOutputStream(os);
// 创建文件缓冲区
byte[] b = new byte[1024];
int len = 0;
/// 文件开始传输,输出提示语句
System.out.println("start");
while ((len = fis.read(b)) != -1) {
bos.write(b, 0, len);
}
// 传输完成输出提示语句
System.out.println("clear");
bos.close();
fis.close();
}
}
}
接收端(客户端)
public class MyClient {
public static void main(String[] args) throws UnknownHostException, IOException {
//连接到指定ip,指定端口的服务
Socket s = new Socket("192.168.4.198",8888);
//获取基于Socket的字节输入流
InputStream is = s.getInputStream();
//创建文件缓冲流
BufferedInputStream bis = new BufferedInputStream(is);
//创建本地接收文件
File f = new File("C:/Users/admin/Desktop/2.jpg");
FileOutputStream fos = new FileOutputStream(f);
//创建文件接收缓冲区
byte[] b = new byte[1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
}
//文件传输完成
System.out.println("clear");
bis.close();
fos.close();
s.close();
}
}