You are basically reading the contents of the file when you select it, discard the contents and then trying to send the last int
value you read from it to the server. A file my be many, many, many bytes long (think giga bytes), an int
ins't going to hold that much information (poor int
).
Instead, when the user selects a File
, you should maintain a reference to it until you actually need it...
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == b) {
int x = fc.showOpenDialog(null);
if (x == JFileChooser.APPROVE_OPTION) {
fileToBeSent = fc.getSelectedFile();
tf.setText(f1.getAbsolutePath());
b1.setEnabled(true);
} else {
fileToBeSent = null;
tf.setText(null;);
b1.setEnabled(false);
}
}
if (e.getSource() == b1) {
send();
}
} catch (Exception ex) {
}
}
When the user presses the "send" button, you would simply copy the file input stream to the sockets output stream...
FileInputStream in = null;
try {
in = new FileInputStream(fileToBeSent);
byte[] buffer = new byte[1024];
int bytesIn = -1;
while ((bytesIn = in.read(buffer)) != -1) {
dout.write(buffer, 0, bytesIn);
}
dout.flush();
} finally {
try {
in.close();
} catch (Exception exp) {
}
}
That should at least get you one step closer.
The next problem you are likely to hit is the fact that the UI will stop responding while the transfer is underway.
In this case, you should take a look at Concurrency in Swing.
Modern UI's need to deal with many different characteristics of client machines, included different fonts, font rendering capabilities, DPI, screen resolutions and lots more. You're putting your self in a very dark and deep hole by using absolute layouts.
You should take advantage of the layout manager API which is designed to easy the pressure of these concerns and make you UI more accommodating on different operating environments.
Take a look at Layout out Components within a Container for more deatils
You may also want to take a closer look at Basic I/O and All about sockets for more details...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…