Java File to String fileToStream(File source, OutputStream target)

Here you can find the source of fileToStream(File source, OutputStream target)

Description

file To Stream

License

Open Source License

Declaration

public static void fileToStream(File source, OutputStream target) 

Method Source Code


//package com.java2s;
/*/*  w ww . j  av  a  2  s .  c  om*/
 * Copyright 2016 janobono. All rights reserved.
 * Use of this source code is governed by a Apache 2.0
 * license that can be found in the LICENSE file.
 */

import java.io.*;

public class Main {
    public static void fileToStream(File source, OutputStream target) {
        try (InputStream is = new BufferedInputStream(new FileInputStream(source));
                OutputStream os = new BufferedOutputStream(target)) {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while (bytesRead != -1) {
                bytesRead = is.read(buffer);
                if (bytesRead > 0) {
                    os.write(buffer, 0, bytesRead);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] read(File file) {
        try (InputStream is = new BufferedInputStream(new FileInputStream(file));
                ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while (bytesRead != -1) {
                bytesRead = is.read(buffer);
                if (bytesRead > 0) {
                    os.write(buffer, 0, bytesRead);
                }
            }
            return os.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void write(File file, byte[] data) {
        try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file, false))) {
            os.write(data, 0, data.length);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. fileToStr(String strInput)
  2. fileToStream(final File file)
  3. fileToStream(String filename)
  4. fileToString(File f)
  5. fileToString(File f)