Java、二进制编辑器

该程序使用JavaFX创建了一个简单的GUI,用户可以输入文件路径来读取和保存文件的二进制内容。文本区域显示读取的文件内容,点击按钮可将文本区的内容保存回文件。程序处理了文件不存在的情况,并实现了文本的可折行显示。
摘要由CSDN通过智能技术生成

 

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());
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值