java 中 byte[]、file、inputstream 互相转换

java 中 byte[]、File、InputStream 互相转换

  • 将File、FileInputStream 转换为byte数组:

    1
    2
    3
    4
    5
    6
    7
    File file = new File("test.txt");

    InputStream input = new FileInputStream(file);

    byte[] byt = new byte[input.available()];

    input.read(byt);
  • 将byte数组转换为InputStream:

    1
    2
    3
    byte[] byt = new byte[1024];

    InputStream input = new ByteArrayInputStream(byt);
  • 将byte数组转换为File :

    1
    2
    3
    4
    5
    6
    7
    File file = new File('');

    OutputStream output = new FileOutputStream(file);

    BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);

    bufferedOutput.write(byt);

人生两苦:想要却不得,拥有却失去。 –褚禄山
珍惜当下,与君共勉~