skip to Main Content

I have this command split -b 1800k file_name.tar.gz but don’t know how to use this in Dart or Flutter.

I have a tar.gz file and I want to split it into multiple files in JSON format. Is this possible in Dart?

For example,
One original File: file_name.tar.gz

After splitting:
file_name_1.json, file_name_2.json, file_name_3.json, file_name_4.json, file_name_5.json

2

Answers


  1. Chosen as BEST ANSWER

    I got the solution for this

    I have made the below Function to Split files into multiple segments.

    Future<List<File>> splitFileInSegment(File file,
          {int chunkSize = 1800,
          required String cachePath,
          required String fileName}) async {
        int sizeOfFile = chunkSize * 1024;
        ByteData bd = await rootBundle.load(file.path);
        List<int> bytes = bd.buffer.asUint8List();
    
        List<List<int>> splitBytes = [];
    
        int isHalfFileNeeded = bytes.length % sizeOfFile;
        int numberOfFiles = bytes.length ~/ sizeOfFile;
        if (isHalfFileNeeded > 0) {
          numberOfFiles = numberOfFiles + 1;
        }
        int offset = 0;
    
        for (int i = 0; i < numberOfFiles; i++) {
          int getLastIndex = 0;
    
          int bytesReached = (i + 1) * sizeOfFile;
          if (bytesReached <= bytes.length) {
            getLastIndex = bytesReached;
          } else {
            getLastIndex = offset + isHalfFileNeeded;
          }
    
          List<int> byteList = bytes.sublist(offset, getLastIndex);
          splitBytes.add(byteList);
          offset += sizeOfFile;
        }
    
        List<File> files = [];
    
        for (int index = 0; index < splitBytes.length; index++) {
          final File tempFile = File("$cachePath/$fileName" + "_" + "$index.json");
    
          File file = await tempFile.writeAsBytes(splitBytes[index]);
          files.add(file);
        }
    
        return files;
      }
    

  2. import 'dart:io';
    
    void main() {
    
      File originalFile = File('file_name.tar.gz');
    
      List<int> bytes = originalFile.readAsBytesSync();
    
      int chunkSize = 1800 * 1024; // 1800 KB
    
      int numOfFiles = (bytes.length / chunkSize).ceil();
    
      for (int i = 0; i < numOfFiles; i++) {
    
        int start = i * chunkSize;
    
        int end = (i + 1) * chunkSize;
    
        if (end > bytes.length) {
    
          end = bytes.length;
    
        }
    
        List<int> chunk = bytes.sublist(start, end);
    
        File newFile = File('file_name_${i + 1}.json');
    
        newFile.writeAsBytesSync(chunk);
    
      }
    
      print('File split into $numOfFiles JSON files.');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search