我正在尝试实现LZW压缩和解压缩技术。 我的程序将任何文件作为InputStream并将其读入字节数组。 然后它将压缩算法应用于它,编码的字节以字符串变量返回。
然后我应用解压缩算法,返回原始数字。
现在为了检索原始文件,我必须将此字符串的内容传输到字节数组中,然后将此数组写入输出流。
将解压缩字符串的内容复制到字节数组是我的问题所在。
File file = new File("aaaa.png");
byte[] data = new byte[(int) file.length()];
try{
FileInputStream in = new FileInputStream(file);
in.read(data);
in.close();
for(int i= 0; i< data.length;i++){
System.out.print("original = " + data[i]);
}
String ax = Arrays.toString(data);
List<Integer> compressed = compress(ax);
System.out.println("compressed = " + compressed);
String decompressed= new String(decompress(compressed));
System.out.println("decompressed = " + decompressed);
// Copy string contents into byte array arr[]
File file2 = new file("aaaa.png");
FileOutputStream out = new FileOutputStream(file2);
out.write(arr);
out.close();
}
catch(Exception e){
System.out.println("Error!");
e.printStackTrace();
}
到目前为止我的代码的输出看起来有点链接 -
orignal = -119807871131026100001373726882000170001686000 .....
压缩= [91,45,49,49,57,44,32,56,48,261,55,56,265,49,261,49,51,270,264,32,50,54, 273,261,274,280,270,272,32,55,283,55,50,261,54,267,262,......]
decompressed = [-119,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,17,0,0 ,0,16,8,6,0,0,0,-16,49,-108,95,0,0,0,1,115,82,71,66,0,-82,-50,28 ,-23,0,0,0,4,103,65,77,65,0,0,-79,-113,11,-4,97,5,0,0,0,32,99,72 ,......]
请帮我弄清楚如何将字符串的内容复制到字节数组中。 谢谢!
答案 0 :(得分:1)
字符串到字节[]反之亦然可以这样转换:
String string = "Hello!";
byte[] array;
//String to byte[]
array = string.getBytes();
//byte[] to String
string = new String(array);
如果我理解你,你将用字节数值解析字符串。
String decompressed = "[-119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72]";
String[] input = decompressed.replaceAll("[\\[\\]]", "").split(", ");
byte[] output = new byte[input.length];
for (int i = 0; i < input.length; i++) {
output[i] = Byte.parseByte(input[i]);
}
System.out.println(new String(output));
输出为PNG
和一些非打印字符。
答案 1 :(得分:0)
感谢百万@Sergey Fedorov。 你的回复的第二部分为我工作。
String[] input = decompressed.replaceAll("[\\[\\]]", "").split(", ");
byte[] output = new byte[decompressed.length()];
for (int i = 0; i < input.length; i++) {
output[i] = Byte.parseByte(input[i]);
System.out.print(output[i]);
}