Last active
May 4, 2018 22:39
-
-
Save kishida/ccf37679612c9210281e05e66cec8246 to your computer and use it in GitHub Desktop.
File Editor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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