1. 程式人生 > >Java字串和輸入流的相互轉換

Java字串和輸入流的相互轉換

在讀取網路資源時經常要用到字串和輸入流之間的相互轉化,找到了些方法,記錄一下。

將字串轉化為輸入流,程式碼如下:

public static InputStream getStringStream(String sInputString){

  if (sInputString != null && !sInputString.trim().equals("")){

      try{

          ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());

          return tInputStringStream;

      }catch (Exception ex){

          ex.printStackTrace();

      }

  }

  return null;

}
將輸入流轉化會字串,程式碼如下:
public static String getStreamString(InputStream tInputStream){

  if (tInputStream != null){

       try{

            BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(tInputStream));

            StringBuffer tStringBuffer = new StringBuffer();

            String sTempOneLine = new String("");

            while ((sTempOneLine = tBufferedReader.readLine()) != null){

                tStringBuffer.append(sTempOneLine);

            }

           return tStringBuffer.toString();

      }catch (Exception ex){

           ex.printStackTrace();

      }

  }

  return null;

}

或者是以下的方法,程式碼如下:

public class StreamTool {
	/**
	 * 把輸入流的內容轉化成字串
	 * @param is
	 * @return
	 */
	public static String readInputStream(InputStream is){
		try {
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			int length=0;
			byte[] buffer=new byte[1024];
			while((length=is.read(buffer))!=-1){
				baos.write(buffer, 0, length);
			}
			is.close();
			baos.close();
			//或者用這種方法
			//byte[] result=baos.toByteArray();
			//return new String(result);
			return baos.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "獲取失敗";
		}
	}
}