Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7950649
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T02:20:16+00:00 2026-06-04T02:20:16+00:00

I have been looking around for an answer to this, but couldn’t really find

  • 0

I have been looking around for an answer to this, but couldn’t really find anything on it. Earlier today, I asked how I could make a File into a String through a byte array, and then back again, for retrieval later.

What people told me, was that I had to just store the byte array, to avoid nasty encoding issues. So now I’ve started working on that, but I have now hit a wall.

Basically, I used unbuffered streams before, to turn a file into a byte array. This works good in theory, but it takes up a lot of memory which eventually will cast the heap size exception. I should use buffered streams instead (or so I am told), and the problem I have now, is going from a BufferedInputStream to a byte[]. I’ve tried to copy and use the methods found in this documentation

http://docs.guava-libraries.googlecode.com/git/javadoc/index.html?com/google/common/io/package-summary.html

Where I exchange unbuffered streams for buffered streams. The only issue, is that I can’t directly turn a buffered output stream into a byte array, as I can with an unbuffered stream.

Help? 🙂

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public final class BufferedByteStream {

    private static final int BUF_SIZE = 1024000;

    public static long copy(BufferedInputStream from, BufferedOutputStream to) throws IOException { 
        byte[] buf = new byte[BUF_SIZE];
        long total = 0;
        while(true) {
            int r = from.read(buf);
            if(r == -1) {
                break;
            }
            to.write(buf, 0, r);
            total += r;
        }
        return total;
    }

    public static byte[] toByteArray(BufferedInputStream in) throws IOException {
        BufferedOutputStream out = new BufferedOutputStream(new ByteArrayOutputStream());
        copy(in, out);
        return out. // <--- Problem is here
    }
}

EDIT:

I am still getting Heap Space errors. So I will now post all the code:

main.java

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import jserver.io.BufferedByteStream;
/**
*
* @author Vipar
*/
public class main {
    public static void main(String[] args) {
    File f = new File("<doesn't matter>");
        try {
            byte[] buf;
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f))) {
                buf = BufferedByteStream.toByteArray(bis);
                bis.close();
            }
            File f2 = new File("<doesn't matter>");
            try (FileOutputStream fos = new FileOutputStream(f2)) {
                fos.write(buf);
                fos.close();
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

BufferedByteStream.java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public final class BufferedByteStream {

    private static final int BUF_SIZE = 1024000;

    public static long copy(BufferedInputStream from, BufferedOutputStream to) throws IOException { 
        byte[] buf = new byte[BUF_SIZE];
        long total = 0;
        while(true) {
            int r = from.read(buf);
            if(r == -1) {
                break;
            }
            to.write(buf, 0, r);
            total += r;
        }
        return total;
    }

    public static byte[] toByteArray(BufferedInputStream in) throws IOException {
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        BufferedOutputStream out = new BufferedOutputStream(bytesOut);
        copy(in, out);
        return bytesOut.toByteArray();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T02:20:18+00:00Added an answer on June 4, 2026 at 2:20 am

    Have a look at ByteArrayOutputStream:
    Java 7 API java.io.ByteArrayOutputStream

    bytesOut = new ByteArrayOutputStream();
    byte[] bytes = bytesOut.toByteArray();
    

    Update:
    If you insist on doing what you are doing you can just assign the intermediate ByteArrayOutputStream to a variable and get hold of the array that way:

    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream()
    BufferedOutputStream out = new BufferedOutputStream(bytesOut);
    copy(in, out);
    return bytesOut.toByteArray();
    

    Update 2:
    The real question seems to be how to copy a file without reading it all into memory first:

    1) Manually:

        byte[] buff = new byte[64*1024]; //or some size, can try out different sizes for performance
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("fromFile"));
        BufferedOutputStream out = new BufferedOutputStream(new FileoutputStream("toFile"));
        int n = 0;
        while ((n = in.read(buff)) >= 0) {
            out.write(buff, 0, n);
        }
        in.close();
        out.close();
    

    2) Efficiently by the OS and no loop etc:

    FileChannel from = new FileInputStream(sourceFile).getChannel();
    FileChanngel to = new FileOutputStream(destFile).getChannel();
    to.transferFrom(from, 0, from.size());
    //or from.transferTo(0, from.size(), to);
    from.close();
    to.close();
    

    3)
    If you have Java 7 you can simplify exception and stream closing or just copy the file with the new APIs i in java 7:

    java.nio.file.Files.copy(...);
    

    see java.nio.file.Files

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been looking around for this but couldn't find an answer anywhere, so
I have been looking around the web for this but cannot really find a
I have been looking around for an answer to my question but couldn't find
Hi guys I have been looking around for the answer to this but have
I have been looking around for an answer to this, but haven't been able
I have been looking around for some time now, but can't seem to find
Now, I have been looking for the answer to this for a while, but
I've been looking around for a while for an answer to this, but haven't
I have been looking around ocn Google and Stackoverflow but haven't found what I
I have been looking around for awhile now and I can't seem to find

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.