• String与InputStream相互转换


    1.String to InputStream

      public static InputStream String2InputStream(String name) {
        return new ByteArrayInputStream(name.getBytes());
      }

    2.InputStream to String

        这里提供几个方法。

     1   public static String InputStream2String(InputStream input,String encode) throws IOException {
     2     StringBuilder builder = new StringBuilder();
     3 
     4     InputStreamReader reader = new InputStreamReader(input,encode);
     5     BufferedReader bufferedReader = new BufferedReader(reader);
     6     String line = null;
     7     try {
     8       while ((line = bufferedReader.readLine()) != null) {
     9         builder.append(line);
    10       }
    11     } catch (IOException e) {
    12       e.printStackTrace();
    13     } finally {
    14       input.close();
    15     }
    16     return builder.toString();
    17   }
    18 
    19   public static String InputStream2String2(InputStream input) throws IOException {
    20     StringBuffer buffer = new StringBuffer();
    21     byte[] b = new byte[1024];
    22     int n;
    23     try {
    24       while ((n = input.read(b)) != -1) {
    25         buffer.append(new String(b, 0, n));
    26       }
    27     } catch (IOException e) {
    28       e.printStackTrace();
    29     } finally {
    30       input.close();
    31     }
    32     return buffer.toString();
    33   }
    34 
    35   public static String InputStream2String3(InputStream input) throws IOException {
    36     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    37     int i;
    38     try {
    39       while ((i = input.read()) != -1) {
    40         outputStream.write(i);
    41       }
    42     } catch (IOException e) {
    43       e.printStackTrace();
    44     } finally {
    45       input.close();
    46     }
    47     return outputStream.toString();
    48   }
  • 相关阅读:
    Win10+Ubuntu18.04 UEFI启动模式SSD+HDD
    Chap1:全景图[Computer Science Illuminated]
    [IDE] ECLIPSE取消自动更新
    [Unit Test] Unit Test Brief Introduction
    [ English ] 俚语 “Ping me=打我电话”
    Some Useful Resources for the Future Usage
    python错误记录
    django-用户认证模型
    Djiango-富文本编辑器
    Djiango-建立模型抽象基类
  • 原文地址:https://www.cnblogs.com/liyiran/p/5649318.html
Copyright © 2020-2023  润新知