这个是我个人写代码的时候做的一些记录,错误估计很多。嘿嘿,大家看到了希望能指正
package com.aosa.test;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 4444);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
String fileName = dataInputStream.readUTF();
//本地文件路径
File file = new File("D://" + fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
while(dataInputStream.read(buffer) != -1){
fileOutputStream.write(buffer);
}
dataInputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.aosa.test;
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 Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(4444);
while(true){
Socket socket = serverSocket.accept();
File file = new File("F://JUDE(JAVA建模软件).rar");
String fileName = file.getName();
FileInputStream fileInputStream = new FileInputStream(file);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
//向客户端输文件
dataOutputStream.writeUTF(fileName);
byte[] buffer = new byte[1024];
while(fileInputStream.read(buffer) != -1){
dataOutputStream.write(buffer);
}
//dataOutputStream.writeUTF("false");
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}