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) –