将一个短视频从byte []转换为String并检索并将这些字节重新转换为Video [关闭]

问题描述 投票:-3回答:2

我的要求:

  1. 从视频文件中获取所有字节。
  2. 放入一个字符串。
  3. 从该字符串重新构建视频

1:[正常工作]

private static byte[] readBytesFromFile(String filePath) {
    FileInputStream fileInputStream = null;
    byte[] bytesArray = null;
    try {
        File file = new File(filePath);
        bytesArray = new byte[(int) file.length()];

        //read file into bytes[]
        fileInputStream = new FileInputStream(file);
        fileInputStream.read(bytesArray);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return bytesArray;
}

public static void main(String[] args){
    byte[] bFile= readBytesFromFile("an mp4 video file in my system");
}

Source

对于2.和3:

FileOutPutStream out = new FileOutPutStream ("to Re-convert mp4 video path");

如果我写,

out.write(bFile);
out.close();

- >它的工作原理

但这并不是我所需要的。

我需要一些东西:

byte[] bytes = bFile;
String s = new String(bytes, Charset.defaultCharset());
bFile = s.getBytes(Charset.defaultCharset());

然后 :

    out.write(bFile);
    out.close();

- >不起作用。

怎么实现这个?

java mp4
2个回答
2
投票

你不能指望这样的事情发挥作用

new String(bytes, Charset.defaultCharset());

因为你不能指望任意字节序列来表示字符串的有效编码。

你应该选择一个字符串编码,其中任何字节序列代表一个有效的编码,或者更好的是,转换为像Base64这样的东西


-2
投票

我写了这个应用程序。我认为它是独立于系统的(在我的环境中工作 - windows 10,jdk 9,默认UTF-8。我希望它能以某种方式帮助你:

public class SOFlow {

public static void main(String[] args) {

    byte[] allBytes = new byte[256];
    for (int i = 0; i < allBytes.length; i++) {
        allBytes[i] = (byte) i;

    }

    System.out.println("allBytes  " + Arrays.toString(allBytes));

    String strAllBytes = convertBytesArrayToString(allBytes);
    System.out.println("converted " + Arrays.toString(convertStringToBytesArray(strAllBytes)));
    System.out.println("String " + strAllBytes);
    System.out.println("String len " + strAllBytes.length());


}

public static String convertBytesArrayToString(byte[] bytesArray) {
    CharBuffer charBuff = ByteBuffer.wrap(bytesArray).asCharBuffer();
    return charBuff.toString();
}

public static byte[] convertStringToBytesArray(String str) {

    //IMHO, char in String always take TWO bytes (16 bits), while byte size is 8 bits
    //so, we have to 'extract' first 8 bites to byte and second 8 bites to byte

    byte[] converted = new byte[str.length() << 1]; //just half of str.lenght
    char strChar;
    int position;
    for (int i = 0; i < str.length(); i++) {
        strChar = str.charAt(i);
        position = i << 1;
        converted[position] = (byte) ((strChar & 0xFF00) >> 8); //mask and shift
        converted[position + 1] = (byte) (strChar & 0x00FF); //mask
    }
    return converted;
}

}

© www.soinside.com 2019 - 2024. All rights reserved.