java读取视频数据并写入另一个文件

Kri*_*ish 1 java file-io copy file video-streaming

我正在读取一个以字节为单位的视频文件数据并将其发送到另一个文件,但收到的视频文件无法正常播放并且断断续续。

谁能解释一下为什么会发生这种情况,并感谢解决方案。

我的代码如下

import java.io.*;

public class convert {

  public static void main(String[] args) {

    //create file object
    File file = new File("B:/music/Billa.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("B://music//a.mp4");
       BufferedWriter bw=new BufferedWriter(new FileWriter(dest));
       bw.write(strFileContent+"\n");
       bw.flush();

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

Jak*_*ula 5

这个问题可能已经死了,但有人可能会发现这很有用。

您无法将视频作为字符串处理。这是使用 Java 7 或更高版本读取和写入(复制)任何文件的正确方法。

请注意,缓冲区的大小取决于处理器,通常应为 2 的幂。有关更多详细信息,请参阅此答案

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileCopy {
public static void main(String args[]) {
    
    final int BUFFERSIZE = 4 * 1024;
    String sourceFilePath = "D:\\MyFolder\\MyVideo.avi";
    String outputFilePath = "D:\\OtherFolder\\MyVideo.avi";

    try(
            FileInputStream fin = new FileInputStream(new File(sourceFilePath));
            FileOutputStream fout = new FileOutputStream(new File(outputFilePath));
            ){
        
        byte[] buffer = new byte[BUFFERSIZE];
        
        while(fin.available() != 0) {
            bytesRead = fin.read(buffer);
            fout.write(buffer, 0, bytesRead);
        }
        
    }
    catch(Exception e) {
        System.out.println("Something went wrong! Reason: " + e.getMessage());
    }

    }
}
Run Code Online (Sandbox Code Playgroud)