有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将包含大整数的文件拆分为两个相等的部分?

我想把一个大整数文件分成两个相等的部分

下面是我用随机大整数生成的一个文件

public void generateRandomBigInteger(){

    if(file.length() > 0){
        System.out.println("Sobreescriptura de fitxer no permesa!\n");
    }
    else {
        //try-with-resources per asegurar el tancament del stream
        try {
            int tamany = 6;
            FileOutputStream fos = new FileOutputStream(file, true);
            DataOutputStream dos = new DataOutputStream(fos);

            for (int i = 0; i < tamany; i++){
                BigIntegerIO.writeBigInteger(new NumberGenerator().generateBigInteger(), dos);
            }

        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("Numeros aleatoris generats correctament!!\n");
    }

}

我有这个方法来分割文件,但不是正确的方法

public void splitFile() throws IOException {

    //Definir el tamany de les noves parts (tamany del file numeros.txt / 2)
    long fileSize = file.length();// 166,03 kB
    double sizeOfFiles = fileSize/2;// 83,01kB
    byte[] buffer = new byte[(int) sizeOfFiles +1];

    //Obtendre el nome de file sense ".txt"
    String fileName = file.getName();
    //String fileName = name.replaceFirst("[.][^.]+$", "");

    //Nombrar les parts 1, 2, ...
    int partCounter = 1;
    int cantitatBytes;
    //try-with-resources per asegurar el tancament del stream
    try{
        FileInputStream fis = new FileInputStream(file);
        DataInputStream bis = new DataInputStream(fis);
        while((cantitatBytes = bis.read(buffer)) > 0){
            //escriviu cada tros de dades en un fitxer separat amb un nombre diferent en nom
            String nomPartFitxer = String.format ("%s.%01d", fileName, partCounter++);
            File newFile = new File(nomPartFitxer);

            FileOutputStream fos = new FileOutputStream(newFile);
            //try-with-resources per asegurar el tancament del stream
            try(DataOutputStream dos = new DataOutputStream(fos)){
                dos.write(buffer, 0, cantitatBytes);
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("");
}

共 (0) 个答案