---------------------------------------------------------------------------------------------------------------------------------------
服务端
---------------------------------------------------------------------------------------------------------------------------------------
package socket.file;
import java.io.*;
import java.net.*;
public class FileServer {
private static String basePath;
public static void main(String[] args){
ServerSocket ss = null;
Socket sc = null;
FileOutputStream fos = null;
try {
ss = new ServerSocket(2222);//创建端口
sc = ss.accept();//进入阻塞
BufferedInputStream bis = new BufferedInputStream(sc.getInputStream());//反冲区
byte[] b = new byte[512];//接收文件名
bis.read(b);//读取文件名
fos = new FileOutputStream("src/");//目标路径
String fileName = new File(new String(b).trim()).getName();
String filePath = basePath + fileName;
for (int k = bis.read(); k != -1; fos.write(b), k = bis.read())
;
fos.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if (null != fos) {
fos.close();
}
if (null != fos) {
fos.close();
}
if (null != sc) {
sc.close();
}
if (null != ss) {
ss.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
---------------------------------------------------------------------------------------------------------------------------------------
客户端
---------------------------------------------------------------------------------------------------------------------------------------
package socket.file;
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) {
Socket cs = null;
BufferedOutputStream bos = null;
FileInputStream fis = null;
try {
cs = new Socket("127.0.0.1", 2222);
String filePath = "H:/Photos.jpg";
bos = new BufferedOutputStream(cs.getOutputStream());
byte[] b = new byte[512];
System.arraycopy(filePath.getBytes(), 0, b, 0,
filePath.getBytes().length);// src:源数组;DestPos:目标数组;dest:;destPos:;
bos.write(b);
fis = new FileInputStream(filePath);
for (int k = fis.read(); k != -1; bos.write(k), k = fis.read())
;
bos.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != bos)
bos.close();
if (null != fis)
fis.close();
if (null != cs)
cs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}