package io;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.io.*;
public class Exercise17_13 extends Application {
private TextField numberOfSmallerFile = new TextField(); //小片段数量
private TextField file = new TextField(); //文件名
private Button start = new Button("Start"); //按钮
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
GridPane gridPane = new GridPane(); //网格面板
gridPane.setHgap(5); //面板设置水平间距5
gridPane.addRow(0, new Label("Enter a file:"), file); //面板添加行
gridPane.addRow(1, new Label("Specify the number of smaller files:"), numberOfSmallerFile);
BorderPane pane = new BorderPane(gridPane); //边框面板
pane.setTop(new Label("If the base file is named temp.txt with three pieces,\n" +
"temp.txt.1, temp.txt.2, and temp.txt.3 are combined into temp.txt")); //设置顶部
pane.setBottom(start); //设置底部
BorderPane.setAlignment(pane.getBottom(), Pos.CENTER); //设置底部居中对齐
//按钮注册动作事件
start.setOnAction(event -> {try {handelActionEvent();} catch (Exception ex) {}});
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Exercise17_13");
primaryStage.show();
}
/** 组合文件 */
private void handelActionEvent() throws Exception {
String filePath = file.getText().trim(); //目标文件路径
int number = Integer.parseInt(numberOfSmallerFile.getText().trim()); //片段数量
//创建输入、输出流并将数据输出到目标文件
try(BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath))) {
for (int i = 0; i < number; i++) {
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath + "." + (i + 1)));
byte[] bytes = new byte[128];
int length;
while ((length = inputStream.read(bytes)) != -1)
outputStream.write(bytes, 0, length);
inputStream.close();
}
}
}
}