首页

关于htmlunit源码包中的TextUtil文本工具类进行字符串、InputStream流及字节数组间转换处理

标签:htmlunit,TextUtil,文本工具类,字符串流转换,字符串字节数组转换     发布时间:2018-06-09   

一、前言

关于htmlunit源码包中的com.gargoylesoftware.htmlunit.TextUtil文本字符工具类, 进行字符串转流toInputStream处理、字符串转字节数组处理stringToByteArray等。

二、源码说明

package com.gargoylesoftware.htmlunit;@b@@b@import java.io.ByteArrayInputStream;@b@import java.io.ByteArrayOutputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.io.OutputStreamWriter;@b@import java.io.UnsupportedEncodingException;@b@@b@public final class TextUtil@b@{@b@  public static final String DEFAULT_CHARSET = "ISO-8859-1";@b@@b@  public static InputStream toInputStream(String content)@b@  {@b@    try@b@    {@b@      return toInputStream(content, "ISO-8859-1");@b@    }@b@    catch (UnsupportedEncodingException e) {@b@      throw new IllegalStateException("ISO-8859-1 is an unsupported encoding!  You may have a corrupted installation of java.");@b@    }@b@  }@b@@b@  public static InputStream toInputStream(String content, String encoding)@b@    throws UnsupportedEncodingException@b@  {@b@    ByteArrayOutputStream byteArrayOutputStream;@b@    try@b@    {@b@      byteArrayOutputStream = new ByteArrayOutputStream(content.length() * 2);@b@      OutputStreamWriter writer = new OutputStreamWriter(byteArrayOutputStream, encoding);@b@      writer.write(content);@b@      writer.flush();@b@@b@      byte[] byteArray = byteArrayOutputStream.toByteArray();@b@      return new ByteArrayInputStream(byteArray);@b@    }@b@    catch (UnsupportedEncodingException e) {@b@      throw e;@b@    }@b@    catch (IOException e)@b@    {@b@      throw new IllegalStateException("Exception when converting a string to an input stream: '" + e + "'", e);@b@    }@b@  }@b@@b@  public static byte[] stringToByteArray(String content)@b@  {@b@    return ((content != null) ? stringToByteArray(content, "ISO-8859-1") : null);@b@  }@b@@b@  public static byte[] stringToByteArray(String content, String charset)@b@  {@b@    byte[] contentBytes;@b@    try@b@    {@b@      contentBytes = content.getBytes(charset);@b@    }@b@    catch (UnsupportedEncodingException e) {@b@      contentBytes = new byte[0];@b@    }@b@    return contentBytes;@b@  }@b@}