package com;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
 
public class FileToRar {
private static String rarCmd = "C:/Program Files/WinRAR/WinRAR.exe a ";
public String folderToRar() throws Exception
{
String pathString="C:\\CFLog";
File file=new File(pathString);
String cmd="";
  cmd=rarCmd+file.toString()+".rar"   +" "+file.toString() ;
 //System.out.println(cmd);
 
       try {
       
           Runtime rt = Runtime.getRuntime();
            rt.exec(cmd);
                     
       } catch (Exception e) {
           System.out.println(e.getMessage());
       }
       File file2 = new File(pathString+".rar");
byte[] bytes = getByte(file2);
 
// byte[] bytes = msg.getBytes();
StringBuilder sb = new StringBuilder(bytes.length * 2);
// 转换hex编码
for (byte b : bytes) {
sb.append(Integer.toHexString(b + 0x800).substring(1));
}
//System.out.println(sb.toString());
return sb.toString();
// 转换后的代码为c7d7a3acc4e3bac3
//msg = sb.toString();
//System.out.println(msg);
 
// 再次转换为string
// System.out.println(decode(msg));
// System.out.println(msg);
}
public static byte[] getByte(File file) throws Exception {
byte[] bytes = null;
if (file != null) {
InputStream is = new FileInputStream(file);
int length = (int) file.length();
if (length > Integer.MAX_VALUE) // 当文件的长度超过了int的最大值
{
System.out.println("this file is max ");
return null;
}
bytes = new byte[length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// 如果得到的字节长度和file实际的长度不一致就可能出错了
if (offset < bytes.length) {
System.out.println("file length is error");
return null;
}
is.close();
}
return bytes;
}
 
public static void main(String[] args) throws Exception {
FileToRar testFileToRar= new FileToRar();
//testFileToRar.folderToRar();
System.out.println(testFileToRar.folderToRar());
}
 
}