-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileReceiver1.java
More file actions
61 lines (48 loc) · 1.86 KB
/
Copy pathFileReceiver1.java
File metadata and controls
61 lines (48 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FileReceiver1 extends JFrame {
private JButton receiveFileButton;
public FileReceiver1() {
super("File Receiver (Localhost)");
setLayout(new FlowLayout());
receiveFileButton = new JButton("Receive File");
add(receiveFileButton);
receiveFileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
receiveFile(); // Call the updated method
}
});
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void receiveFile() {
// Set save path to specified directory
String directoryPath = "C:\\Users\\bhara\\OneDrive\\Desktop\\Received file";
File directory = new File(directoryPath);
// Create directory if it doesn't exist
if (!directory.exists()) {
directory.mkdirs();
}
String savePath = directoryPath + "\\received_file.png";
try (Socket socket = new Socket("localhost", 1234); // Fixed port 1234
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
FileOutputStream fileOut = new FileOutputStream(savePath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
fileOut.write(buffer, 0, bytesRead);
}
JOptionPane.showMessageDialog(this, "File received and saved to: " + savePath);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new FileReceiver1();
}
}