Pages

Saturday, 7 January 2017

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

17.20 (Binary 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 binary representation in a text area.
The user can also modify the binary code and save it back to the file

import javafx.scene.input.KeyCode;

import java.io.*;
public class BinaryEditorPane extends FileViewerPane {

    protected File file;

    public BinaryEditorPane() {

        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 += getBits(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..");
        }
    }

    private String getBits(int value) {

        String byteString = "";

        for (int i = 7; i >= 0; i--)
            byteString += ((value >> i) & 1);

        return byteString;
    }
}

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

public class Exercise_20 extends Application {

    public static void main(String[] args) {

        Application.launch(args);

    }

    @Override
    public void start(Stage primaryStage) {


        BinaryEditorPane pane = new BinaryEditorPane();
        primaryStage.setScene(new Scene(pane));
        primaryStage.show();

    }


}

No comments:

Post a Comment