sockets, java sending files server client
I want to send a file through a socket. The "server" is sitting on another computer than mine and the client in another computer as well. The file can go to and fro server and client but only in their current directory. The approach i have taken up to now is by using a file input stream and writing the file on a file output stream neverthelees this doesnt work as far as i understand.. Is there another way to send files through sockets?
Here is my code what could be wrong here?
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"));
// }
}
And some client code :
...
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
boolean exit = false;
else if (sentence.length() > 3 &&a开发者_运维技巧mp; sentence.substring(0, 3).equals("get")) {
String currPath = dir.getCurrentPath();
outToServer.writeBytes(sentence + "_" + currPath + "\n");
} else {
...
Your copyFileToClient
method uses a FileInputStream and FileOutputStream directly, i.e. it does not transfer anything to/from the client at all, only from one local file to another. This is fine if you want to manage remotely files on the server, but does not help for sending data between different computers.
You have to somehow send the data through the OutputStream/InputStream of the Socket - i.e. use the FileInputStream at the sending side and the FileOutputStream at the receiving one.
精彩评论