Transfer file over socket
I found this code witch I tried and it works great but(!). I want to store the file in a folder that I will choose and also get it from a folder that I again will chose. Since the Sender get an argument then I suppose that if I give an argument like /home/user/test.txt then that's ok and it'll work out fine but I don't get how to store the file to a specific folder ( the Server part in other words ). Any ideas?
If I'm wrong about the argument please by all means correct me :D
PS开发者_高级运维: It works just fine for the Netbeans' default folder ( no specification of folder for the Sender or Server ).
Any help appreciated.
Frankly speaking, though i feel bad about doing your homework, I am just in a good mood :)
In the below code(FileReciever) i have added a new variable folder which is initalized from the first argument passed to main(). So the name of the folder you want to save the file in mus tbe passed as the first argument. The only other line I have changed is: File file=new File(folder, file_name);
private String folder = "";
public static void main(String[] args) {
try {
folder = args[0];
ServerSocket listener = new ServerSocket(port);
while (true) {
FileReceiver file_rec = new FileReceiver();
file_rec.socket = listener.accept();
new Thread(file_rec).start();
}
}
catch (java.lang.Exception ex) {
ex.printStackTrace(System.out);
}
}
public void run() {
try {
InputStream in = socket.getInputStream();
int nof_files = ByteStream.toInt(in);
for (int cur_file=0;cur_file < nof_files; cur_file++) {
String file_name = ByteStream.toString(in);
File file=new File(folder, file_name);
ByteStream.toFile(in, file);
}
}
catch (java.lang.Exception ex) {
ex.printStackTrace(System.out);
}
}
精彩评论