package io;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.*;
public class Exercise17_20 extends Application {
private TextField textField = new TextField();
private TextArea textArea = new TextArea();
private Button button = new Button("Save the change");
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
HBox topHBox = new HBox(5, new Label("Enter a file:"), textField); //顶部
topHBox.setAlignment(Pos.CENTER); //居中对齐
textField.setPrefColumnCount(26); //文本域设置列数
textArea.setPrefRowCount(6);
textArea.setPrefColumnCount(30);
textArea.setWrapText(true); //文本区域可折行
//文本域、按钮注册动作事件
textField.setOnAction(event -> {try {setTextArea();} catch (Exception ex) {}});
button.setOnAction(event -> {try {saveToFile();} catch (Exception ex) {}});
BorderPane pane = new BorderPane(new ScrollPane(textArea));
pane.setTop(topHBox);
pane.setBottom(button);
BorderPane.setAlignment(pane.getBottom(), Pos.CENTER);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Exercise17_20");
primaryStage.show();
}
/** 设置文本区域信息 */
private void setTextArea() throws IOException {
File file = new File(textField.getText().trim()); //文件对象
if (!file.exists()) //如果文件不存在
textArea.setText("No such file exists");
else { //否则
textArea.setText(""); //设置原有信息为空
try(DataInputStream inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)))) {
try {
while (true) //文本区域追加文本
textArea.appendText(Integer.toBinaryString(inputStream.readByte()));
} catch (EOFException ex) {
}
}
}
}
/** 回存到文件 */
private void saveToFile() throws IOException {
File file = new File(textField.getText().trim());
if (!file.exists())
textArea.setText("No such file exists");
else {
try(DataOutputStream outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)))) {
outputStream.writeUTF(textArea.getText().trim());
}
}
}
}