可引用jar包,commons-io.jar
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
继承org.apache.commons.io.FileUtils
package com.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class FileUtils extends org.apache.commons.io.FileUtils {
public static String in2Str(InputStream in, Charset charset) throws IOException {
if (in == null) {
return null;
}
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(in, charset.name());
int tmp;
char temp;
while ((tmp = reader.read()) != -1) {
temp = (char) tmp;
sb.append(temp);
}
} finally {
in.close();
}
return sb.toString();
}
/**
* 将输入流(InputStream)转为byte数组,读取完后输入流(InputStream)即被关闭
*
* @param in 输入流
* @return 返回byte数组
* @throws IOException
*/
public static byte[] in2Bytes(InputStream in) throws IOException {
if (in == null) {
return null;
}
ByteArrayOutputStream out = null;
byte[] bytes = null;
try {
out = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
bytes = out.toByteArray();
} finally {
if (out != null) {
out.close();
}
in.close();
}
return bytes;
}
}