2
我目前正在使用Java套接字。我创建了一个服务器端代码和客户端代码来通过套接字传输文件。我已经在同一个系统中成功地将文件从客户端传输到服务器,但是如果我尝试在不同平台上使用不同的系统,那么它不起作用。服务器端和客户端代码如下所示。如何使用IOUtils.copy通过Java套接字传输文件
服务器端代码
public class FileTransferTestServer extends Thread{
private final Socket socket;
public FileTransferTestServer(Socket socket) {
// TODO Auto-generated constructor stub
this.socket = socket;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ServerSocket serverSocket = new ServerSocket(5000);
Socket socket = serverSocket.accept();
System.out.println("Connection Established with "+socket.getInetAddress().getHostAddress());
new FileTransferTestServer(socket).start();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run(){
try {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String buffer = null;
String fileName = null;
if((buffer = br.readLine()) != null){
fileName = buffer;
}
FileOutputStream fos = new FileOutputStream(fileName);
int res = IOUtils.copy(is, fos);
System.out.println("res : "+res);
is.close();
fos.flush();fos.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端代码
public class FileTransferClient {
public FileTransferClient() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Socket socket = new Socket("172.16.4.23",5000);
File file = new File("/Users/Guest/Desktop/DQM.txt");
OutputStream outputStream = socket.getOutputStream();
PrintWriter out = new PrintWriter(outputStream);
out.println("file-transfer");
out.flush();
out.println(""+file.getName());
out.flush();
FileInputStream fis = new FileInputStream(file);
int res = IOUtils.copy(fis, outputStream);
out.flush();
outputStream.flush();
outputStream.close();
fis.close();
System.out.println("res : "+res);
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如何使这一方案,系统之间传输文件
我已经在Windows(服务器)& Mac OS X的尝试(客户端)和Windows(服务器)& LinuxMint(客户端)
说明: 1.我想发送文件名,然后是文件内容。 2.文件内容可以是任何形式(文本或二进制文件)
您能否给一些代码片段,请。 –
@GowthamShanmugaraj我已经更新了我的答案。 –
是的,它的工作:)。谢谢[Peter Lawrey](http://stackoverflow.com/users/57695/peter-lawrey) –