Skip to content

Instantly share code, notes, and snippets.

@kishida
Last active May 4, 2018 22:39
Show Gist options
  • Save kishida/ccf37679612c9210281e05e66cec8246 to your computer and use it in GitHub Desktop.
Save kishida/ccf37679612c9210281e05e66cec8246 to your computer and use it in GitHub Desktop.
File Editor
package kis.sample;
import java.awt.BorderLayout;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class FileEditor {
public static void main(String[] args) {
var f = new JFrame("editor");
var textarea = new JTextArea();
f.add(textarea);
var p = new JPanel();
f.add(BorderLayout.NORTH, p);
var loadButton = new JButton("Load");
loadButton.addActionListener(ae -> {
var dialog = new JFileChooser();
if (dialog.showOpenDialog(f) != JFileChooser.APPROVE_OPTION) {
return;
}
String separator = System.getProperty("line.separator");
Path selected = dialog.getSelectedFile().toPath();
try {
List<String> lines = Files.readAllLines(selected);
textarea.setText("");
lines.forEach(line -> textarea.append(line + "\n"));
} catch (IOException ex) {
ex.printStackTrace();
}
});
p.add(loadButton);
var saveButton = new JButton("Save");
saveButton.addActionListener(ae -> {
var dialog = new JFileChooser();
if (dialog.showSaveDialog(f) != JFileChooser.APPROVE_OPTION) {
return;
}
String separator = System.getProperty("line.separator");
Path selected = dialog.getSelectedFile().toPath();
try {
Files.write(selected, List.of(
textarea.getText().replace("\n", separator)));
} catch (IOException ex) {
ex.printStackTrace();
}
});
p.add(saveButton);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 300);
f.setVisible(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment