目录
题目:**17.20 (二进制编辑器)
编写一个GUI应用程序,让用户在文本域输入一个文件名,然后单击回车键,在文本区域显示它的二进制表示形式。用户也可以修改这个二进制代码,然后将它回存到这个文件中,如图17-23a所示。
代码示例
编程练习题17_20BinaryEditor.java
java
package chapter_17;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class 编程练习题17_20BinaryEditor extends Application{
private TextField tfInput;
private TextArea textArea;
private String FilePath;
@Override
public void start(Stage primaryStage) throws Exception {
VBox vBox = getPane();
tfInput.setOnKeyPressed(e ->{
if(e.getCode() == KeyCode.ENTER) {
try{
readFile();
}catch (IOException ex) {
ex.printStackTrace();
}
}
});
Scene scene = new Scene(vBox);
primaryStage.setTitle("编程练习题17_20BinaryEditor");
primaryStage.setScene(scene);
primaryStage.show();
}
public VBox getPane() {
VBox vBox = new VBox();
tfInput = new TextField();
tfInput.setPrefWidth(300);
Label lbInput = new Label("Enter a file:",tfInput);
lbInput.setContentDisplay(ContentDisplay.RIGHT);
textArea = new TextArea();
Button btSave = new Button("Save the change");
btSave.setOnAction(e ->{
try {
saveFile();
}catch (IOException ex) {
ex.printStackTrace();
}
});
vBox.setAlignment(Pos.CENTER);
vBox.getChildren().addAll(lbInput,tfInput,textArea,btSave);
return vBox;
}
public void readFile() throws IOException{
FilePath = tfInput.getText().replaceAll("\\\\", "/");
if(!FilePath.isEmpty()) {
try(
FileInputStream input = new FileInputStream(FilePath);
){
int read;
while((read = input.read()) != -1) {
if (read == '\n') { // 仅检查 \n
textArea.appendText("\n");
}else
textArea.appendText(getBits(read)+" ");
}
}
}
}
public void saveFile() throws IOException {
if (!FilePath.isEmpty()) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(FilePath))) {
String text = textArea.getText();
String[] s = text.split(" ");
for(String str:s) {
if(str.contains("\n")) {
writer.write("\n");
}
int i = binaryStringToDecimal(str);
writer.write((char)i);
}
}
}
}
public static int binaryStringToDecimal(String binary) {
// 将二进制字符串转换为十进制整数
int decimal = 0;
for (int i = 0; i < binary.length(); i++) {
int bit = binary.charAt(i) - '0'; // 将字符'0'或'1'转换为整数0或1
decimal = decimal * 2 + bit;
}
// 将十进制整数转换为字符串
return decimal;
}
public static String getBits(int value) {
String str = "";
for(int i = 7; i >= 0; i--) {
int temp = value >> i;
int bit = temp & 1;
str += bit;
}
return str;
}
public static void main(String[] args) {
Application.launch(args);
}
}
结果展示
C:\Users\Lenovo\eclipse-workspace\JavaFX\src\Text\Exercise17_20.txt
修改前/修改后