# Complete Java File Editor with Network Integration
Here's a comprehensive solution that:
1. Connects to a network server
2. Uses JFileChooser to load/edit local text files
3. Downloads files to the connected server
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
public class NetworkFileEditor extends JFrame {
private JTextArea textArea;
private JFileChooser fileChooser;
private File currentFile;
private JTextField serverField;
private JButton connectButton;
private boolean isConnected = false;
private String serverUrl;
public NetworkFileEditor() {
setTitle("Network Text File Editor");
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create components
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
// Network connection panel
JPanel networkPanel = new JPanel(new FlowLayout());
serverField = new JTextField("http://localhost:8080/upload", 30);
connectButton = new JButton("Connect");
networkPanel.add(new JLabel("Server URL:"));
networkPanel.add(serverField);
networkPanel.add(connectButton);
// File operation buttons
JButton openButton = new JButton("Open File");
JButton saveButton = new JButton("Save Locally");
JButton downloadButton = new JButton("Upload to Server");
downloadButton.setEnabled(false);
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(saveButton);
buttonPanel.add(downloadButton);
// Status bar
JLabel statusLabel = new JLabel("Status: Disconnected");
// Add components to frame
add(networkPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
add(statusLabel, BorderLayout.SOUTH);
// Initialize file chooser
fileChooser = new JFileChooser();
fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("Text Files", "txt"));
// Add action listeners
connectButton.addActionListener(e -> connectToServer(statusLabel));
openButton.addActionListener(e -> openFile(statusLabel));
saveButton.addActionListener(e -> saveFile(statusLabel));
downloadButton.addActionListener(e -> uploadToServer(statusLabel));
}
private void connectToServer(JLabel statusLabel) {
serverUrl = serverField.getText().trim();
if (serverUrl.isEmpty()) {
statusLabel.setText("Status: Please enter server URL");
return;
}
connectButton.setEnabled(false);
connectButton.setText("Connecting...");
statusLabel.setText("Status: Connecting to server...");
new SwingWorker<Boolean, Void>() {
@Override
protected Boolean doInBackground() throws Exception {
try {
URL url = new URL(serverUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
connection.setConnectTimeout(5000);
int responseCode = connection.getResponseCode();
return responseCode == HttpURLConnection.HTTP_OK;
} catch (Exception e) {
return false;
}
}
@Override
protected void done() {
try {
if (get()) {
isConnected = true;
connectButton.setText("Connected");
statusLabel.setText("Status: Connected to server");
((JButton) getContentPane().getComponent(2).getComponent(2)).setEnabled(true);
} else {
statusLabel.setText("Status: Connection failed");
connectButton.setText("Connect");
connectButton.setEnabled(true);
}
} catch (Exception e) {
statusLabel.setText("Status: Connection error - " + e.getMessage());
connectButton.setText("Connect");
connectButton.setEnabled(true);
}
}
}.execute();
}
private void openFile(JLabel statusLabel) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
currentFile = fileChooser.getSelectedFile();
try (BufferedReader reader = new BufferedReader(new FileReader(currentFile))) {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
textArea.setText(content.toString());
statusLabel.setText("Status: Loaded " + currentFile.getName());
} catch (IOException e) {
statusLabel.setText("Status: Error reading file");
JOptionPane.showMessageDialog(this, "Error reading file: " + e.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void saveFile(JLabel statusLabel) {
if (currentFile == null) {
int returnVal = fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
currentFile = fileChooser.getSelectedFile();
if (!currentFile.getName().toLowerCase().endsWith(".txt")) {
currentFile = new File(currentFile.getAbsolutePath() + ".txt");
}
} else {
return;
}
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(currentFile))) {
writer.write(textArea.getText());
statusLabel.setText("Status: Saved to " + currentFile.getName());
} catch (IOException e) {
statusLabel.setText("Status: Save failed");
JOptionPane.showMessageDialog(this, "Error saving file: " + e.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private void uploadToServer(JLabel statusLabel) {
if (!isConnected) {
statusLabel.setText("Status: Not connected to server");
return;
}
if (textArea.getText().isEmpty()) {
statusLabel.setText("Status: No content to upload");
return;
}
String fileName = JOptionPane.showInputDialog(this,
"Enter filename for server (with .txt extension):",
"serverfile.txt");
if (fileName == null || fileName.trim().isEmpty()) {
statusLabel.setText("Status: Upload cancelled");
return;
}
new SwingWorker<Boolean, Void>() {
@Override
protected Boolean doInBackground() throws Exception {
try {
URL url = new URL(serverUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
try (OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8)) {
osw.write(textArea.getText());
}
int responseCode = connection.getResponseCode();
return responseCode == HttpURLConnection.HTTP_OK;
} catch (Exception e) {
return false;
}
}
@Override
protected void done() {
try {
if (get()) {
statusLabel.setText("Status: File uploaded successfully");
} else {
statusLabel.setText("Status: Upload failed");
}
} catch (Exception e) {
statusLabel.setText("Status: Upload error - " + e.getMessage());
}
}
}.execute();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
NetworkFileEditor editor = new NetworkFileEditor();
editor.setVisible(true);
});
}
}
```
## Key Features:
1. **Network Connection**:
- Verifies server connection before enabling upload
- Shows real-time connection status
- Uses SwingWorker for non-blocking network operations
2. **File Operations**:
- Load text files using JFileChooser
- Save files locally with automatic .txt extension
- Edit files in a large text area
3. **Server Upload**:
- Uploads edited text files to the connected server
- Allows custom filename specification
- Properly handles UTF-8 encoding
4. **User Feedback**:
- Status bar shows current operation status
- Error messages for failed operations
- Progress feedback during network operations
## How to Use:
1. Enter your server URL (e.g., "http://yourserver.com/upload")
2. Click "Connect" to establish connection
3. Use "Open File" to load a local text file
4. Edit the content in the text area
5. Save locally with "Save Locally" or upload to server with "Upload to Server"
## Server Requirements:
The server should:
- Accept POST requests at the specified URL
- Handle text/plain content type
- Process the "Content-Disposition" header for filename
- Return HTTP 200 OK on success
Would you like me to modify any specific part of this implementation or explain any component in more detail?
No comments:
Post a Comment