Pages

Saturday, 7 January 2017

Chapter 17 Exercise 21, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

17.21 (Hex editor)
Write a GUI application that lets the user enter a file name
in the text field and press the Enter key to display its hex
representation in a text area. The user can also modify the
hex code and save it back to the file.


import javafx.scene.input.KeyCode;

import java.io.*;

public class HexEditorPane extends FileViewerPane {

    protected File file;

    public HexEditorPane() {

        tfFilePath.setOnKeyPressed(e -> {
            if (e.getCode() == KeyCode.ENTER)
                loadFile();
        });
        btnSave.setOnAction(e -> save());

    }

    private void loadFile() {
        file = new File(tfFilePath.getText());

        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file), 25000)) {

            String s = "";
            int r;
            while ((r = in.read()) != -1)
                s += Integer.toHexString(r);

            taContent.setText(s);
        } catch (FileNotFoundException ex) {
            System.out.println("Error: File not found! Try using an absolute path.");
        } catch (IOException ex) {
            System.out.println("Error reading file...");
        }
    }

    private void save() {

        try (BitOutputStream out = new BitOutputStream(file)) {

            out.writeBit(taContent.getText());

        } catch (IOException ex) {
            System.out.println("Error saving file..");
        }
    }
}

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Exercise_21 extends Application {

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        HexEditorPane pane = new HexEditorPane();
        primaryStage.setScene(new Scene(pane));
        primaryStage.show();
    }

}

No comments :

Post a Comment