0

I am trying to append two or more mp4 files that I am retrieving (downloading) from the server. The problem is that the last downloaded mp4 file overrides all proceeded downloaded mp4 files.

here is my code:

public class Main {
static Socket socket;
static PrintWriter out;

static List<String> filenamesForDownloads = new ArrayList<>();
static List<String> deviceResponsesForDownloads = new ArrayList<>();

static AtomicReference<FileOutputStream> fileOutputStream = new AtomicReference<>();
static File fileToSave;

static AtomicInteger count = new AtomicInteger(1);

public static void main(String... args) {
    filenamesForDownloads.add("2021_07_04_02_20_14_F_47.mp4");
    filenamesForDownloads.add("2021_07_04_13_15_43_F_47.mp4");
    if (establishSocketConnection()) {
        ExecutorService executorServiceRead = Executors.newFixedThreadPool(1);
        executorServiceRead.execute(readFromSocket());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.execute(() -> {

            String strAppDirectoryPath = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            fileToSave = new File(strAppDirectoryPath, "my_video.mp4");

            if (fileToSave.exists()) {
                fileToSave.delete();
            }

            try {
                fileToSave.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                fileOutputStream.set(new FileOutputStream(fileToSave, true));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            for (String file : filenamesForDownloads) {
                if (socket != null && socket.isConnected()) {
                    out.println("FRequiest," + file);
                }
            }
        });
    } else {
        System.out.println("not connected");
    }

}


private static Boolean establishSocketConnection() {
    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress("192.168.43.1", 5050), 8000);

        out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
        return true;
    } catch (IOException e) {
        // ToDo: Add logging
        return false;
    }
}

private static Runnable readFromSocket() {
    return () -> {
        String response;
        try {
            BufferedReader inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while ((response = inputStream.readLine()) != null) {
                if (response.startsWith("FReceive")) {
                    downloadAllFiles(response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    };
}

private static void downloadAllFiles(String response) {
    System.out.println(response);
    String filename = "";
    int fileSize = 0;
    String dataServerIp = "";
    int dataServerPort = 3001;
    String[] fileParams;

    int bufferLength;
    Socket socket = null;

    String[] serverIPs;

    InetAddress serveraddr = null;
    InputStream inputstram = null;

    fileParams = response.split(",");
    if (fileParams.length >= 6) {
        filename = fileParams[4];
        fileSize = Integer.valueOf(fileParams[5]);
        dataServerIp = fileParams[2];
        dataServerPort = Integer.valueOf(fileParams[3]);
    }
    serverIPs = dataServerIp.split(";");

    try {
        serveraddr = InetAddress.getByName(serverIPs[0]);
        socket = new Socket(serveraddr, dataServerPort);

        inputstram = socket.getInputStream();
        byte[] buffer = new byte[1024];

        while ((bufferLength = inputstram.read(buffer, 0, buffer.length)) > 0) {
            fileOutputStream.get().write(buffer, 0, bufferLength);

        }
        System.out.println(count.get());
        if(count.get() == filenamesForDownloads.size()) {
            fileOutputStream.get().close();
            System.out.println("finish all");
        }
        count.set(count.get() + 1);
        socket.close();
    } catch (Exception exc) {
        //ToDo: return downloadStatus
        System.out.println(exc.getMessage());
    }
  }
}

fileOutputStream.set(new FileOutputStream(fileToSave, true)); should allow appending bytes to the file but in my case it is always overwriting mp4 over and over. How can I apply actual appending to the file?

Khaled
  • 345
  • 5
  • 14
  • 1
    merging video files by simply appending them into a single file is certainly not going to work – Raildex Jul 11 '21 at 14:14
  • how can I make it working? I mean how can I achieve the functionality? – Khaled Jul 11 '21 at 14:22
  • You need software such as ffmpeg that knows how to concatenate multimedia files. Or for pure Java try [Xuggler](https://stackoverflow.com/questions/19812480/java-xuggler-combine-an-mp3-audio-file-and-a-mp4-movie) – g00se Jul 11 '21 at 14:27

0 Answers0