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

利用java Socket发送,接收文件.

2014-05-15 23:07 369 查看
客户端.

package net.demo;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SendFile {
public static void main(String[] args) throws Exception {
new SendFile().sendFile(null, "D:\\a.jpg", 8821);

}

public void sendFile(String romteUrl, String path, int port)
throws Exception {

File file = getFile(path);
Socket scket = new Socket("localhost",port);
DataOutputStream dos = new DataOutputStream(scket.getOutputStream());
DataInputStream dis = new DataInputStream(new BufferedInputStream(
new FileInputStream(path)));

int size = 1024;
byte[] bufArry = new byte[size];
dos.writeUTF(file.getName());
dos.flush();
dos.writeLong(file.length());
dos.flush();

while (true) {
int read = 0;
if (dis != null) {
read = dis.read(bufArry);
}

if (read == -1) {
break;
}

dos.write(bufArry, 0, read);

}
dos.flush();

close(dis, dos, scket, null);

}

public void close(DataInputStream dis, DataOutputStream dos,
Socket sockect, ServerSocket ss) {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

if (sockect != null) {
try {
sockect.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

if (ss != null) {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public File getFile(String path){
File file = new File(path);
return file;
}

}


服务端

package net.demo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class RecFile {
public static void main(String[] args) throws Exception {
new RecFile().recFile("F:\\", "localhost", 8821);
}

public void recFile(String savePath, String ip, int port) throws Exception {
ServerSocket socket = new ServerSocket(port);
Socket s = socket.accept();
DataInputStream dis = new DataInputStream(new BufferedInputStream(
s.getInputStream()));
int size = 1024;

byte[] buf = new byte[size];
int passedlen = 0;
long len = 0;

savePath += dis.readUTF();
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(savePath)));
len = dis.readLong();
System.out.println("len:" + len +" KB");
System.out.println("开始接收!");
while(true){
int read = 0;
if(dis != null){
read = dis.read(buf);
}
passedlen += read;
if(read == -1){
break;
}
System.out.println("文件接收了" + (passedlen * 100 / len) + "%");
fileOut.write(buf, 0, read);
}
System.out.println("接收完成..." + savePath);
fileOut.close();

}

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