Add 'sdk/java-v2/' from commit '55f103e336ca9fb8bf1720d2ef4ee8dd4e221118'
[arvados.git] / sdk / java-v2 / src / main / java / org / arvados / client / utils / FileSplit.java
1 /*
2  * Copyright (C) The Arvados Authors. All rights reserved.
3  *
4  * SPDX-License-Identifier: AGPL-3.0 OR Apache-2.0
5  *
6  */
7
8 package org.arvados.client.utils;
9
10 import org.apache.commons.io.FileUtils;
11
12 import java.io.*;
13 import java.util.ArrayList;
14 import java.util.List;
15
16 /**
17  * Based on:
18  * {@link} https://stackoverflow.com/questions/10864317/how-to-break-a-file-into-pieces-using-java
19  */
20 public class FileSplit {
21
22     public static List<File> split(File f, File dir, int splitSize) throws IOException {
23         int partCounter = 1;
24
25         long sizeOfFiles = splitSize * FileUtils.ONE_MB;
26         byte[] buffer = new byte[(int) sizeOfFiles];
27
28         List<File> files = new ArrayList<>();
29         String fileName = f.getName();
30
31         try (FileInputStream fis = new FileInputStream(f); BufferedInputStream bis = new BufferedInputStream(fis)) {
32             int bytesAmount = 0;
33             while ((bytesAmount = bis.read(buffer)) > 0) {
34                 String filePartName = String.format("%s.%03d", fileName, partCounter++);
35                 File newFile = new File(dir, filePartName);
36                 try (FileOutputStream out = new FileOutputStream(newFile)) {
37                     out.write(buffer, 0, bytesAmount);
38                 }
39                 files.add(newFile);
40             }
41         }
42         return files;
43     }
44 }