我的要求:
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");
}
对于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();
- >它不起作用。
如何实现这个?
答案 0 :(得分:2)
你不能指望这样的事情发挥作用
new String(bytes, Charset.defaultCharset());
因为您不能指望任意字节序列表示字符串的有效编码。
你应该选择一个字符串编码,其中任何字节序列代表一个有效的编码,或者更好的是,转换为像Base64这样的东西
答案 1 :(得分:-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;
}
}