示例#1
0
 /**
  * 将流的内容写入文件<br>
  *
  * @param dest 目标文件
  * @param in 输入流
  * @throws IOException
  */
 public static void writeStream(File dest, InputStream in) throws IOException {
   FileOutputStream out = null;
   try {
     out = new FileOutputStream(dest);
     IoUtil.copy(in, out);
   } finally {
     close(out);
   }
 }
示例#2
0
  @Test
  public void readShouldReadInputStreamCorrectlyAndShouldCloseStream() throws Exception {
    // Read content shorter than buffer size ...
    String content = "This is the way to grandma's house.";
    InputStream stream = new ByteArrayInputStream(content.getBytes());
    InputStreamWrapper wrapper = new InputStreamWrapper(stream);
    assertThat(wrapper.isClosed(), is(false));
    assertThat(IoUtil.read(wrapper), is(content));
    assertThat(wrapper.isClosed(), is(true));

    // Read content longer than buffer size ...
    for (int i = 0; i != 10; ++i) {
      content += content; // note this doubles each time!
    }
    stream = new ByteArrayInputStream(content.getBytes());
    wrapper = new InputStreamWrapper(stream);
    assertThat(wrapper.isClosed(), is(false));
    assertThat(IoUtil.read(wrapper), is(content));
    assertThat(wrapper.isClosed(), is(true));
  }
示例#3
0
  @Test
  public void readShouldReadReaderCorrectlyAndShouldCloseStream() throws Exception {
    // Read content shorter than buffer size ...
    String content = "This is the way to grandma's house.";
    Reader reader = new StringReader(content);
    ReaderWrapper wrapper = new ReaderWrapper(reader);
    assertThat(wrapper.isClosed(), is(false));
    assertThat(IoUtil.read(wrapper), is(content));
    assertThat(wrapper.isClosed(), is(true));

    // Read content longer than buffer size ...
    for (int i = 0; i != 10; ++i) {
      content += content; // note this doubles each time!
    }
    reader = new StringReader(content);
    wrapper = new ReaderWrapper(reader);
    assertThat(wrapper.isClosed(), is(false));
    assertThat(IoUtil.read(wrapper), is(content));
    assertThat(wrapper.isClosed(), is(true));
  }
示例#4
0
  /**
   * post方式请求数据.发送的是json数据
   *
   * @param url
   * @param params
   * @return
   */
  public static String sendhttpByPost(String url, String params) {

    HttpPost httpRequest = new HttpPost(url);
    httpRequest.addHeader("Accept-Encoding", "gzip");
    httpRequest.addHeader("Content-Type", "application/json");
    String strResult = null;
    try {

      // 发出HTTP request
      //			httpRequest.setEntity(new StringEntity(params, "UTF-8"));
      //			System.out.println("post发送的params是:" + params);
      //			url =

      HttpClient httpClient = null;
      // 判断请求协议方式
      if (url.startsWith("https://")) {
        // 取得HTTP response
        httpClient = HttpUtil.wrapClient(new DefaultHttpClient());
      } else {
        httpClient = new DefaultHttpClient();
      }
      // https请求方式
      HttpResponse httpResponse = httpClient.execute(httpRequest);
      // 若状态码为200 ok
      // Content-Encoding
      if (httpResponse.getStatusLine().getStatusCode() == 200) {
        Header[] headers = httpResponse.getHeaders("Content-Encoding");
        boolean isUseGzip = false;
        for (Header header : headers) {
          if ("Content-Encoding".equals(header.getName())) {
            if ("gzip".equalsIgnoreCase(header.getValue())) {
              isUseGzip = true;
            }
          }
        }
        if (isUseGzip) {
          strResult =
              IoUtil.convertStreamToString(
                  new GZIPInputStream(httpResponse.getEntity().getContent()));
        } else {
          strResult = EntityUtils.toString(httpResponse.getEntity());
        }
      } else {
        return null;
      }

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }

    return strResult;
  }
示例#5
0
 /**
  * 发送 url get请求 创建URL,并使用URLConnection/HttpURLConnection
  *
  * @param url
  * @return
  */
 public static String sendGetByURLConn(String url) {
   String result = "";
   DefaultHttpClient client = new DefaultHttpClient();
   HttpGet get = new HttpGet(url);
   get.addHeader("Accept-Encoding", "gzip");
   // get.setHeaders(headers);Content-Encoding
   try {
     HttpResponse response = client.execute(get);
     System.out.println(response.getStatusLine().getStatusCode());
     if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
       Header[] headers = response.getHeaders("Content-Encoding");
       boolean isUseGzip = false;
       for (Header header : headers) {
         if ("Content-Encoding".equals(header.getName())) {
           if ("gzip".equalsIgnoreCase(header.getValue())) {
             isUseGzip = true;
           }
         }
       }
       if (isUseGzip) {
         result =
             IoUtil.convertStreamToString(new GZIPInputStream(response.getEntity().getContent()));
       } else {
         result = EntityUtils.toString(response.getEntity());
       }
       return result;
     }
   } catch (ClientProtocolException e) {
     e.printStackTrace();
     return null;
   } catch (IOException e) {
     e.printStackTrace();
     return null;
   }
   return null;
 }
示例#6
0
  /**
   * 复制文件<br>
   * 如果目标文件为目录,则将源文件以相同文件名拷贝到目标目录
   *
   * @param src 源文件
   * @param dest 目标文件或目录
   * @param isOverride 是否覆盖目标文件
   * @throws IOException
   */
  public static void copy(File src, File dest, boolean isOverride) throws IOException {
    // check
    if (!src.exists()) {
      throw new FileNotFoundException("File not exist: " + src);
    }
    if (!src.isFile()) {
      throw new IOException("Not a file:" + src);
    }
    if (equals(src, dest)) {
      throw new IOException("Files '" + src + "' and '" + dest + "' are equal");
    }

    if (dest.exists()) {
      if (dest.isDirectory()) {
        dest = new File(dest, src.getName());
      }
      if (dest.exists() && !isOverride) {
        throw new IOException("File already exist: " + dest);
      }
    }

    // do copy file
    FileInputStream input = new FileInputStream(src);
    FileOutputStream output = new FileOutputStream(dest);
    try {
      IoUtil.copy(input, output);
    } finally {
      close(output);
      close(input);
    }

    if (src.length() != dest.length()) {
      throw new IOException(
          "Copy file failed of '" + src + "' to '" + dest + "' due to different sizes");
    }
  }
示例#7
0
 /**
  * Write the entire contents of the supplied string to the given writer. This method always
  * flushes and closes the writer when finished.
  *
  * @param content the content to write to the writer; may be null
  * @param writer the writer to which the content is to be written
  * @throws IOException
  * @throws IllegalArgumentException if the writer is null
  */
 public static void write(String content, Writer writer) throws IOException {
   IoUtil.write(content, writer);
 }
示例#8
0
 /**
  * Write the entire contents of the supplied string to the given stream. This method always
  * flushes and closes the stream when finished.
  *
  * @param content the content to write to the stream; may be null
  * @param stream the stream to which the content is to be written
  * @throws IOException
  * @throws IllegalArgumentException if the stream is null
  */
 public static void write(String content, OutputStream stream) throws IOException {
   IoUtil.write(content, stream);
 }
示例#9
0
 /**
  * Read and return the entire contents of the supplied {@link InputStream}. This method always
  * closes the stream when finished reading.
  *
  * @param stream the streamed contents; may be null
  * @return the contents, or an empty string if the supplied stream is null
  * @throws IOException if there is an error reading the content
  */
 public static String read(InputStream stream) throws IOException {
   return IoUtil.read(stream);
 }
示例#10
0
 /**
  * Read and return the entire contents of the supplied {@link Reader}. This method always closes
  * the reader when finished reading.
  *
  * @param reader the reader of the contents; may be null
  * @return the contents, or an empty string if the supplied reader is null
  * @throws IOException if there is an error reading the content
  */
 public static String read(Reader reader) throws IOException {
   return IoUtil.read(reader);
 }
示例#11
0
 @Test
 public void readShouldReturnEmptyStringForNullReader() throws Exception {
   assertThat(IoUtil.read((Reader) null), is(""));
 }
示例#12
0
 @Test
 public void readShouldReturnEmptyStringForNullInputStream() throws Exception {
   assertThat(IoUtil.read((InputStream) null), is(""));
 }
示例#13
0
 @Test
 public void readBytesShouldReturnEmptyByteArrayForNullInputStream() throws Exception {
   assertThat(IoUtil.readBytes((InputStream) null), is(new byte[] {}));
 }