目录
题目:**17.21 (十六进制编辑器)
代码示例
结果展示
题目:**17.21 (十六进制编辑器)
编写一个 GUI 应用程序,让用户在文本域输入一个文件名,然后按回车键,在文本域显示它的十六进制表达形式。用户也可以修改十六进制代码,然后将它回存到这个文件中,如图17-23b所示。
-
代码示例
编程练习题17_21HexEditor.java
package chapter_17;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
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_21HexEditor 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_21HexEditor");
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(getHex(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 = hexStringToDecimal(str);
writer.write((char)i);
}
}
}
}
public static int hexStringToDecimal(String hex) {
return Integer.parseInt(hex,16);
}
public static String getHex(int value) {
return Integer.toHexString(value);
}
public static void main(String[] args) {
Application.launch(args);
}
}
-
结果展示
C:\Users\Lenovo\eclipse-workspace\JavaFX\src\Text\Exercise17_21.txt
修改前/修改后