一. InputStream转换为String
转换的过程是:
- 使用FileInputStream读取文件流;
- 使用InputStreamReader读取FileInputStream流;
- 使用BufferedReader读取InputStreamReader;
- 每次读取一行BufferedReader,遍历。
具体代码如下:
String template="D;//test.txt"; FileInputStream fileInputStream=null; InputStream in=null; BufferedReader tBufferedReader=null; StringBuffer tStringBuffer=new StringBuffer();//转换为的字符串 try { fileInputStream = new FileInputStream(template); tBufferedReader = new BufferedReader(new InputStreamReader(fileInputStream)); String sTempOneLine = new String(""); while ((sTempOneLine = tBufferedReader.readLine()) != null){ tStringBuffer.append(sTempOneLine); } }catch(Exception e){ e.printStackTrace(); } finally{ try { tBufferedReader.close(); fileInputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
二. String转换为InputStream
转换过程需要借助ByteArrayInputStream读取字符串的字节码,ByteArrayInputStream是InputStream的子类,强制转换即可。
代码如下:
String template="abcdef"; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(template.getBytes()); InputStream inputStream=(InputStream)byteArrayInputStream;
时间: 2024-10-16 10:32:02