各大网站上不少,留着自己用得着上来复制下,网上好多例子操作流写完了后面不关闭的,这点感觉会存在隐患,也是提醒自己多注意
/**
* 从输入流中获取数据(二进制)
*
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // 1K 缓冲区
int len = 0;
while ((len = inStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, len);
}
outStream.close();
return outStream.toByteArray();
}
/**
* 网络获取输出流
*
* @param url
* @return
* @throws IOException
*/
public static InputStream getInputStreamFromUrl(String url)throws IOException
{
URL u = new URL(url);
URLConnection conn = u.openConnection();
InputStream inputStream = conn.getInputStream();
return inputStream;
}
/**
* InputStream --> String
*
* @param is
* @return
* @throws IOException
*/
public static String inputStreamToString(InputStream is) throws IOException
{
// InputStream is = new FileInputStream(new File("text.txt"));
BufferedReader in = new BufferedReader(new InputStreamReader(is,"UTF-8"), 8192);
StringBuffer sb = new StringBuffer();
String line = null;
while (null != (line = in.readLine()))
{
sb.append(line + "\n");
}
is.close();
return sb.toString();
}
/**
* String --> InputStream
*
* @param str
* @return
*/
public static InputStream stringToInputStream(String str)
{
ByteArrayInputStream inStream = new ByteArrayInputStream(str.getBytes());
return inStream;
}
/**
* InputStream --> File
*
* @param is
* @param file
* @throws IOException
*/
public static void inputStreamToFile(InputStream is, File file)throws Exception
{
OutputStream os = new FileOutputStream(file);
int len = -1;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer, 0, 8192)) != -1)
{
os.write(buffer, 0, len);
}
os.close();
}
/**
* File --> InputStream
*
* @param file
* @return
* @throws IOException
*
*/
public static InputStream fileToInputStream(File file) throws IOException
{
InputStream inStream = new FileInputStream(file);
return inStream;
}
/** 写入文件 **/
public static void writeFile(String path, String content)
{
FileOutputStream outStream = null;
try
{
outStream = new FileOutputStream(path);
outStream.write(content.getBytes());
outStream.close();
} catch (Exception e)
{
e.printStackTrace();
} finally
{
if (outStream != null)
{
outStream=null;
}
}
}
/** 读文件内容 **/
public static String readFile(String path)
{
StringBuffer sb = new StringBuffer();
FileInputStream fis =null;
try
{
File file = new File(path);
if (!file.exists() || file.isDirectory())
{
throw new FileNotFoundException();
}
fis = new FileInputStream(file);
byte[] buf = new byte[1024];
while ((fis.read(buf)) != -1)
{
sb.append(new String(buf));
buf = new byte[1024];// 重新生成,避免和上次读取的数据重复
}
fis.close();
} catch (Exception e)
{
e.printStackTrace();
}finally
{
if(null!=fis)
{
fis=null;
}
}
return sb.toString();
}