首页 > 解决方案 > 如何在 Java 中将一些文本数据添加到视频文件中

问题描述

我想将一些字符串数据添加到视频文件中,但我不希望视频文件损坏。我想要实现的是:- 1.)将文本添加到视频文件中。2.) 从该视频文件中提取文本。

我尝试的是:-

public class VideoData{

            public static void main(String[] args) {

    //create file object
    File file = new File("I:/java/MyFolder/SmallVideo.mp4");

    try
    {
      //create FileInputStream object
      FileInputStream fin = new FileInputStream(file);


       byte fileContent[] = new byte[(int)file.length()];
       fin.read(fileContent);

       //create string from byte array
       String strFileContent = new String(fileContent);

       System.out.println("File content : ");
       System.out.println(strFileContent);

       File dest=new File("I://java//OtherFolder//SmallVideo.mp4");
       BufferedWriter bw=new BufferedWriter(new FileWriter(dest));
       bw.write(strFileContent + "\nThis is my Text");
       bw.flush();

    }
    catch(FileNotFoundException e)
    {
      System.out.println("File not found" + e);
    }
    catch(IOException ioe)
    {
      System.out.println("Exception while reading the file " + ioe);
    }
  }
}

请帮助我完成上述任务。

标签: javafileencryptionvideofile-io

解决方案


MP4 文件是存储正确编码的视频、音频、图像和字幕的容器。这是一个具有标准格式规范的二进制文件,这意味着您不能简单地向其中添加任何额外的数据。修改数据可能会损坏文件,并且解码器(只是视频播放器)可能无法渲染它。

同样在您的代码中,您从 mp4 文件中读取二进制数据并将其转换为字符串。不应该是这样的。视频文件数据必须以二进制模式处理,而不是文本。

我不明白你的实际目标。如果您希望在 MP4 文件中存储一些文本,您可以考虑将其存储在视频文件的元数据部分。有关使用第三方库的示例,请参见此处。

隐写术是一种在图像和视频中嵌入文本的技术。我想这超出了你的范围。


推荐阅读