下面给大家分享一个java的文件传输,,有socket套接字的数据流和文件流进行传输:
文件的服务端:
public class FileServer {
private static final int PORT =2013;
private ServerSocket server;
private Socket client;
private DataInputStream dis;
private FileOutputStream fos;
public FileServer()throws Exception{
try {
try {
server =new ServerSocket(PORT);
while(true){
client = server.accept();
dis =new DataInputStream(client.getInputStream());
//文件名和长度
String fileName = dis.readUTF();
long fileLength = dis.readLong();
fos =new FileOutputStream(new File("G:/" + fileName));
byte[] sendBytes =new byte[1024];
int transLen =0;
System.out.println("----开始接收文件<" + fileName +">,文件大小为<" + fileLength +">----");
while(true){
int read =0;
read = dis.read(sendBytes);
if(read == -1)
break;
transLen += read;
System.out.println("接收文件进度" +100 * transLen/fileLength +"%...");
fos.write(sendBytes,0, read);
fos.flush();
}
System.out.println("----接收文件<" + fileName +">成功-------");
client.close();
}
}catch (Exception e) {
e.printStackTrace();
}finally {
if(dis !=null)
dis.close();
if(fos !=null)
fos.close();
server.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception {
new FileServer();
}
}
public class TextFileServer {
private static final String SERVER_IP ="127.0.0.1";
private static final int SERVER_PORT =2013;
private Socket client;
private FileInputStream fis;
private DataOutputStream dos;
public TextFileServer(){
try {
try {
client =new Socket(SERVER_IP, SERVER_PORT);
//向服务端传送文件o
File file =new File("H:/1.txt");
fis =new FileInputStream(file);
dos =new DataOutputStream(client.getOutputStream());
//文件名和长度
dos.writeUTF(file.getName());
dos.flush();
dos.writeLong(file.length());
dos.flush();
//传输文件
byte[] sendBytes =new byte[1024];
int length =0;
while((length = fis.read(sendBytes,0, sendBytes.length)) >0){
dos.write(sendBytes,0, length);
dos.flush();
}
}catch (Exception e) {
e.printStackTrace();
}finally{
if(fis !=null)
fis.close();
if(dos !=null)
dos.close();
client.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception {
new TextFileServer();
}
}