InputStream與String之間轉換
String轉InputStream
/**
* 將str轉換爲inputStream
* @param str
* @return
*/
public static InputStream str2InputStream(String str) {
ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes());
return is;
}
InputStream轉String
/**
* 將inputStream轉換爲str
* @param is
* @return
* @throws IOException
*/
public static String inputStream2Str(InputStream is) throws IOException {
StringBuffer sb;
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(is));
sb = new StringBuffer();
String data;
while ((data = br.readLine()) != null) {
sb.append(data);
}
} finally {
br.close();
}
return sb.toString();
}
InputStream與File之間轉換
File轉InputStream
/**
* 將file轉換爲inputStream
* @param file
* @return
* @throws FileNotFoundException
*/
public static InputStream file2InputStream(File file) throws FileNotFoundException {
return new FileInputStream(file);
}
InputStream轉File
/**
* 將inputStream轉化爲file
* @param is
* @param file 要輸出的文件目錄
*/
public static void inputStream2File(InputStream is, File file) throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(file);
int len = 0;
byte[] buffer = new byte[8192];
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
} finally {
os.close();
is.close();
}
}