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_11 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) throws Exception {
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 you split a file named temp.txt into 3 smaller files,\nthe three " +
"smaller files are temp.txt.1, temp.txt.2, and temp.txt.3")); //设置顶部
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_11");
primaryStage.show();
}
/** 分片存储文件 */
private void handelActionEvent() throws Exception {
String filePath = file.getText().trim(); //源文件路径
int number = Integer.parseInt(numberOfSmallerFile.getText().trim()); //分片数量
long fileSize = (new File(filePath).length() / number) + 1; //片段文件大小
try(RandomAccessFile accessFile = new RandomAccessFile(filePath, "r")) {
for (int i = 0; i < number; i++) {
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath + "." + (i + 1)));
try {
for (long j = 0; j < fileSize+1; j++)
outputStream.write(accessFile.readByte());
} catch (Exception ex) {
} finally {
outputStream.close();
}
}
}
}
}