我想通過套接字發送文件。 「服務器」位於另一臺計算機上,而另一臺計算機上則位於另一臺計算機上。該文件可以來回服務器和客戶端,但只能在他們當前的目錄中。我所採取的方法是通過使用文件輸入流並將文件寫入文件輸出流neverthelees這不工作,據我瞭解..有沒有另一種方式來通過套接字發送文件?套接字,java發送文件服務器客戶端
這是我的代碼這裏有什麼可能是錯的?
public class Copy {
private ListDirectory dir;
private Socket socket;
public Copy(Socket socket, ListDirectory dir) {
this.dir = dir;
this.socket = socket;
}
public String getCopyPath(String file) throws Exception {
String path = dir.getCurrentPath();
path += "\\" + file;
return path;
}
public void copyFileToClient(String file, String destinationPath)
throws Exception {
byte[] receivedData = new byte[8192];
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(getCopyPath(file)));
String findDot = file;
String extension = "";
for (int i = 0; i < findDot.length(); i++) {
String dot = findDot.substring(i, i + 1);
if (dot.equals(".")) {
extension = findDot.substring(i + 1);
}
}
if (extension.equals("")) {
extension = "txt";
}
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(new File(destinationPath + "\\"
+ "THECOPY" + "." + extension)));
int len;
while ((len = bis.read(receivedData)) > 0) {
bos.write(receivedData, 0, len);
}
// in.close();
bis.close();
// output.close();
bos.close();
}
// public static void main(String args[]) throws Exception {
// Copy copy = new Copy();
// System.out.print(copy.getCopyPath("a"));
// }
}
而且一些客戶端代碼:
...
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
boolean exit = false;
else if (sentence.length() > 3 && sentence.substring(0, 3).equals("get")) {
String currPath = dir.getCurrentPath();
outToServer.writeBytes(sentence + "_" + currPath + "\n");
} else {
...
什麼意思是「不起作用」?請更詳細地說明你的問題。 – 2011-05-22 13:06:29