目录
题目:**17.11 (带GUI的分割文件工具)
改写练习题17.10使之带有GUI,如图17-21a所示。
-
习题思路
1. 布局
1.1 创建一个Label用于表示信息。
1.2 创建两个Label和TextField,和一个Button。
1.3 创建一个VBox将节点按顺序放置在布局中。
2. 按钮触发事件,可以使用17.10题中的代码。
编程练习题17.10:
Java语言程序设计基础篇_编程练习题*17.10 (分割文件)-CSDN博客
-
代码示例
编程练习题17_11GUISsplitFile.java
package chapter_17;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import javafx.application.Application;
import javafx.event.ActionEvent;
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.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class 编程练习题17_11GUISsplitFile extends Application{
private Label lbInfo;
private TextField tfFile;
private TextField tfNum;
@Override
public void start(Stage primaryStage) throws Exception {
lbInfo = new Label("If you split a file named temp.txt into 3 smaller files,\n"
+ "the three smaller files are temp.txt.1, temp.txt.2, and temp.txt.3."
);
tfFile = new TextField();
tfNum = new TextField();
Label lbFile = new Label("Enter a file:");
lbFile.setContentDisplay(ContentDisplay.RIGHT);
Label lbNum = new Label("Specify the number of smaller files:");
lbNum.setContentDisplay(ContentDisplay.RIGHT);
Button btStart = new Button("Start");
GridPane gridPane = new GridPane();
gridPane.add(lbFile, 0, 0);
gridPane.add(tfFile, 1, 0);
gridPane.add(lbNum, 0, 1);
gridPane.add(tfNum, 1, 1);
VBox vBox = new VBox(5);
vBox.setAlignment(Pos.CENTER);
vBox.getChildren().addAll(lbInfo, gridPane, btStart);
btStart.setOnMouseClicked(e ->{
try{BTstart();
}catch (IOException ex) {
ex.printStackTrace();
// TODO: handle exception
}
});
Scene scene = new Scene(vBox);
primaryStage.setTitle("编程练习题17_11GUISsplitFile");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
public void BTstart() throws FileNotFoundException,IOException{
String path = tfFile.getText().replaceAll("\\\\", "/");
int num = Integer.parseInt(tfNum.getText());
try (RandomAccessFile raf = new RandomAccessFile(new File(path), "r")) {
long allLength = raf.length();
long splitLength = (allLength + num - 1) / num; // 确保最后一个文件也能包含剩余内容
byte[] buffer = new byte[(int) Math.min(splitLength, Integer.MAX_VALUE)];
int fileIndex = 1;
int bytesRead;
while ((bytesRead = raf.read(buffer)) != -1) {
try (DataOutputStream output = new DataOutputStream(new FileOutputStream("src/Text/Exercise17_11_" + fileIndex + ".txt"))) {
output.write(buffer, 0, bytesRead); // 写入实际读取的字节数
}
fileIndex++;
}
}
}
}
C:\Users\Lenovo\eclipse-workspace\JavaFX\src\Text\Exereise17_11.txt
3
-
输出结果