byte[]跟String的相互转换以及记录日志的各种方法
byte[]和String的相互转换以及记录日志的各种方法
import java.io.*; import java.util.Properties; public class FileFunc { public static String hexStr2String(String bytestr) //字节流(以字符串表示)存储到文件 { int ll=bytestr.length(); if (ll%2!=0) return null; try { byte bt_file[]=new byte[ll/2]; for (int i=0;i<ll/2;i++) { bt_file[i]=(byte)Integer.parseInt(bytestr.substring(i*2,i*2+2),16); } String content=new String(bt_file,0,bt_file.length,"GBK"); return content; } catch (Exception e) { return null; } } public static final byte[] hexStrToBytes(String s) //转换16进制字符串为字节 { byte[] bytes; bytes = new byte[s.length() / 2]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte)Integer.parseInt( s.substring(2 * i, 2 * i + 2), 16); } return bytes; } private static String byte2str(byte b) //一个字节转换成为16进制字符串 { int t; if (b<0) { t=b+256; } else { t=b; } String retval=Integer.toHexString(t).toLowerCase(); if (retval.length()==1) retval="0"+retval; return retval; } public static boolean saveBytes2File(String filename,byte[] bbb) //保存字节流中的数据到文件。 { try { FileOutputStream out=new FileOutputStream(filename); // byte bbb[]=buffer.getBytes("GBK"); out.write(bbb); out.close(); return true; } catch (Exception e) { return false; } } public static void logInfo(String filename,String info) //按照GBK编码保存数据到文件。 { try { FileOutputStream out=new FileOutputStream(filename); byte bt_prompt[]=info.getBytes("GBK"); out.write(bt_prompt); out.close(); } catch (Exception e) { } } public static void logInfo(String filename,String info,boolean append) //按照GBK编码保存数据到文件,如果文件存在,追加数据到文件中。 { try { FileOutputStream out=new FileOutputStream(filename,append); byte bt_prompt[]=info.getBytes("GBK"); out.write(bt_prompt); out.close(); } catch (Exception e) { } } public static void logInfo(String filename,String info,boolean append,String encode) //按照指定编码保存数据到文件,如果文件存在,追加数据到文件中。 { try { FileOutputStream out=new FileOutputStream(filename,append); byte bt_prompt[]=info.getBytes(encode); out.write(bt_prompt); out.close(); } catch (Exception e) { } } public static String getProValue(String path,String name) { String value = ""; try { FileInputStream is=new FileInputStream(new File(path)); Properties props = new Properties(); props.load(is); value = props.getProperty(name); //System.out.println("--value="+value); is.close(); } catch (Exception e) { System.out.println("getProValue:"+e.toString()); } return value; } }