JAVA几个很有用的工具函数

来源:互联网 发布:invalid date js 编辑:程序博客网 时间:2024/05/22 17:32
/** * Logs the message. *  * @param msg *            the message. */private void logMsg(String msg) {DateFormat dateFormat = new SimpleDateFormat("[dd-MM-yyyy HH:mm:ss]: ");Date date = new Date();String oldMsg = mResponseTextView.getText().toString();mResponseTextView.setText(oldMsg + "\n" + dateFormat.format(date) + msg);if (mResponseTextView.getLineCount() > MAX_LINES) {mResponseTextView.scrollTo(0,(mResponseTextView.getLineCount() - MAX_LINES)* mResponseTextView.getLineHeight());}}/** * Logs the contents of buffer. *  * @param buffer *            the buffer. * @param bufferLength *            the buffer length. */private void logBuffer(byte[] buffer, int bufferLength) {String bufferString = "";for (int i = 0; i < bufferLength; i++) {String hexChar = Integer.toHexString(buffer[i] & 0xFF);if (hexChar.length() == 1) {hexChar = "0" + hexChar;}if (i % 16 == 0) {if (bufferString != "") {logMsg(bufferString);bufferString = "";}}bufferString += hexChar.toUpperCase() + " ";}if (bufferString != "") {logMsg(bufferString);}}/** * Converts the HEX string to byte array. *  * @param hexString *            the HEX string. * @return the byte array. */private byte[] toByteArray(String hexString) {int hexStringLength = hexString.length();byte[] byteArray = null;int count = 0;char c;int i;// Count number of hex charactersfor (i = 0; i < hexStringLength; i++) {c = hexString.charAt(i);if (c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'&& c <= 'f') {count++;}}byteArray = new byte[(count + 1) / 2];boolean first = true;int len = 0;int value;for (i = 0; i < hexStringLength; i++) {c = hexString.charAt(i);if (c >= '0' && c <= '9') {value = c - '0';} else if (c >= 'A' && c <= 'F') {value = c - 'A' + 10;} else if (c >= 'a' && c <= 'f') {value = c - 'a' + 10;} else {value = -1;}if (value >= 0) {if (first) {byteArray[len] = (byte) (value << 4);} else {byteArray[len] |= value;len++;}first = !first;}}return byteArray;}/** * Converts the integer to HEX string. *  * @param i *            the integer. * @return the HEX string. */private String toHexString(int i) {String hexString = Integer.toHexString(i);if (hexString.length() % 2 != 0) {hexString = "0" + hexString;}return hexString.toUpperCase();}/** * Converts the byte array to HEX string. *  * @param buffer *            the buffer. * @return the HEX string. */private String toHexString(byte[] buffer) {String bufferString = "";for (int i = 0; i < buffer.length; i++) {String hexChar = Integer.toHexString(buffer[i] & 0xFF);if (hexChar.length() == 1) {hexChar = "0" + hexChar;}bufferString += hexChar.toUpperCase() + " ";}return bufferString;}