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 8194457
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T04:50:04+00:00 2026-06-07T04:50:04+00:00

I got a code from here to write a Int array to file. However,

  • 0

I got a code from here to write a Int array to file. However, I am trying to convert it thus it can write Long array to file. But, it gives error (code given below). Can anybody help me why it is giving error and what should be the corrected code. Thanks.

import java.io.*;
import java.util.ArrayList;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Random;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class Test {
    private static final int bucketSize = 1<<17;//in real world should not be const, but we bored horribly
    static final int zipLevel = 2;//feel free to experiement, higher compression (5+)is likely to be total waste


 static void writes(long[] a, File file, boolean sync) throws IOException{
        byte[] bucket = new byte[Math.min(bucketSize,  Math.max(1<<13, Integer.highestOneBit(a.length >>3)))];//128KB bucket
        byte[] zipOut = new byte[bucket.length];

        final FileOutputStream fout = new FileOutputStream(file);
        FileChannel channel = fout.getChannel();
        try{

            ByteBuffer buf = ByteBuffer.wrap(bucket);
            //unfortunately java.util.zip doesn't support Direct Buffer - that would be the perfect fit
            ByteBuffer out = ByteBuffer.wrap(zipOut);
            out.putLong(a.length);//write length aka header
            if (a.length==0){
                doWrite(channel, out, 0);
                return;
            }

            Deflater deflater = new Deflater(zipLevel, false);
            try{
                for (int i=0;i<a.length;){
                    i = puts(a, buf, i);
                    buf.flip();
                    deflater.setInput(bucket, buf.position(), buf.limit());

                    if (i==a.length)
                        deflater.finish();

                    //hacking and using bucket here is tempting since it's copied twice but well
                    for (int n; (n= deflater.deflate(zipOut, out.position(), out.remaining()))>0;){
                        doWrite(channel, out, n);
                    }
                    buf.clear();
                }

            }finally{
                deflater.end();
            }
        }finally{
            if (sync)
                fout.getFD().sync();
            channel.close();
        }
    }

    static long[] reads(File file) throws IOException, DataFormatException{
        FileChannel channel = new FileInputStream(file).getChannel();
        try{
            byte[] in = new byte[(int)Math.min(bucketSize, channel.size())];
            ByteBuffer buf = ByteBuffer.wrap(in);

            channel.read(buf);
            buf.flip();
            long[] a = new long[(int)buf.getLong()];
            if (a.length==0)
                return a;
            int i=0;
            byte[] inflated = new byte[Math.min(1<<17, a.length*4)];
            ByteBuffer intBuffer = ByteBuffer.wrap(inflated);
            Inflater inflater = new Inflater(false);
            try{
                do{
                    if (!buf.hasRemaining()){
                        buf.clear();
                        channel.read(buf);
                        buf.flip();
                    }
                    inflater.setInput(in, buf.position(), buf.remaining());
                    buf.position(buf.position()+buf.remaining());//simulate all read

                    for (;;){
                        int n = inflater.inflate(inflated,intBuffer.position(), intBuffer.remaining());
                        if (n==0)
                            break;
                        intBuffer.position(intBuffer.position()+n).flip();
                        for (;intBuffer.remaining()>3 && i<a.length;i++){//need at least 4 bytes to form an int
                            a[i] = intBuffer.getInt();
                        }
                        intBuffer.compact();
                    }

                }while (channel.position()<channel.size() && i<a.length);
            }finally{
                inflater.end();
            }
            //          System.out.printf("read ints: %d - channel.position:%d %n", i, channel.position());
            return a;
        }finally{
            channel.close();
        }
    }

    private static void doWrite(FileChannel channel, ByteBuffer out, int n) throws IOException {
        out.position(out.position()+n).flip();
        while (out.hasRemaining())
            channel.write(out);
        out.clear();
    }
    private static int puts(long[] a, ByteBuffer buf, int i) {
        for (;buf.hasRemaining() && i<a.length;){
            buf.putLong(a[i++]);
        }
        return i;
    }





    private static long[] generateRandom(int len){
        Random r = new Random(17);
        long[] n = new long [len];
        for (int i=0;i<len;i++){
            n[i]= r.nextBoolean()?0: r.nextInt(1<<23);//limit bounds to have any sensible compression
        }
        return n;
    }
    public static void main(String[] args) throws Throwable{
        File file = new File("xxx.xxx");
        long[] n = generateRandom(3000000); //{0,2,4,1,2,3};
        long start = System.nanoTime();
        writes(n, file, false);
        long elapsed = System.nanoTime() - start;//elapsed will be fairer if the sync is true

        System.out.printf("File length: %d, for %d ints, ratio %.2f in %.2fms %n", file.length(), n.length, ((double)file.length())/4/n.length, java.math.BigDecimal.valueOf(elapsed, 6) );

        long[] m = reads(file);

        //compare, Arrays.equals doesn't return position, so it sucks/kinda
        for (int i=0; i<n.length; i++){
            if (m[i]!=n[i]){
                System.err.printf("Failed at %d%n",i);
                break;
            }
        }
        System.out.printf("All done!");
    };

}
  • 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-07T04:50:05+00:00Added an answer on June 7, 2026 at 4:50 am

    So I took a few minutes to actually run the code, and it took a little tweaking from your posted code, but here it is.

    One thing I did that was -unnecessary- was change intBuffer to longBuffer, just for clarity’s sake. It’s part of the first difference

    75  -  byte[] inflated = new byte[Math.min(1<<17, a.length*4)];
    76  -  ByteBuffer intBuffer = ByteBuffer.wrap(inflated);
    76  +  byte[] inflated = new byte[Math.min(1<<17, a.length*8)];
    77  +  ByteBuffer longBuffer = ByteBuffer.wrap(inflated);
    

    In the above snippet, I change the length of the inflated buffer to a.length*8 to reflect it being a long array instead of an int array.

    89  -  int n = inflater.inflate(inflated,intBuffer.position(), intBuffer.remaining());
    90  +  int n = inflater.inflate(inflated,longBuffer.position(), longBuffer.remaining());
    

    This is only a change to the variable name.

    92  -  intBuffer.position(intBuffer.position()+n).flip();
    93  -  for (;intBuffer.remaining()>3 && i<a.length;i++){//need at least 4 bytes to form an int
    94  -      a[i] = intBuffer.getInt();
    93  +  longBuffer.position(longBuffer.position()+n).flip();
    94  +  for (;longBuffer.remaining()>7 && i<a.length;i++){//need at least 4 bytes to form an int
    95  +      a[i] = longBuffer.getLong();
    

    This is a very important change. First the name was changed, but that’s not the important part. Second, the remaining() is 7 instead of 3, as bestsss pointed out. Lastly, a[i] is now getting a long instead of an int.. That’s the biggest problem, for sure.

    96  -  intBuffer.compact();
    97  +  longBuffer.compact();
    

    Just a renaming here.

    142 -  System.out.printf("File length: %d, for %d ints, ratio %.2f in %.2fms %n", file.length(), n.length, ((double)file.length())/4/n.length, java.math.BigDecimal.valueOf(elapsed, 6) );
    143 +  System.out.printf("File length: %d, for %d ints, ratio %.2f in %.2fms %n", file.length(), n.length, ((double)file.length())/8/n.length, java.math.BigDecimal.valueOf(elapsed, 6) );
    

    This is just on the file output to get an idea of the compression, it’s now computing the number of results from the file.length / 8 instead of over 4.

    And those are the only necessary edits I had to make to get it to work. Basically just moving from int to long in all places.

    Full code is here in a pastebin in case you muck-up the diff notation or something: http://pastebin.com/emY14Ji4

    Note: the line numbers in my copy (+) are one higher than your copy (-) because of a debug statement I didn’t remove… whoops…

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

Sidebar

Related Questions

I'm trying to create a function to read Morse code from one file, convert
I got some sample code from the net here: http://www.javadb.com/sending-a-post-request-with-parameters-from-a-java-class That works fine. It
first post here, and probably an easy one. I've got the code from Processing's
I got following code from net and it looks everything is proper but i'm
Possible Duplicate: Convert some code from C++ to C I've got some code that
I've got how to copy one file to another from start, but how could
I’m trying to save an array to a .plist file on my iphone but
I got this code from our frontend guy for headings: <h2 class=headline><span>Foobar</span></h2> The span
I got this code from the wordpress <head profile=http://gmpg.org/xfn/11> What does this means? what
I got below code from http://msdn.microsoft.com/en-us/library/dd584174(office.11).aspx for adding custom property in webpart tool pane.

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.