JavaFX、带 GUI的分割文件工具

 


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();
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值