🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.jbuilder.java.language
Article #8467

Re: How can I read in file into a byte array?

#8467
From: Johan Forsberg
Date: Fri, 23 Mar 2001 08:51
44 lines
1920 bytes
"Ben Matterson (Borland)" <bmatterson@borland.com> wrote in message
news:3AB7BC0C.60473976@borland.com...
> Hello,
>
> Maybe this is a dead easy question and I am just dumb.

Yes. Oh wait, I wasn't supposed to say that, right? ;-)

> I need to read a file of indeterminate length into an array of bytes.

The other posters have seems to have missed the easy way:

FileInputStream fis=...;
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int n;
byte buf[1024]; // Or whatever. Larger sizes are probably more efficient.

try {
    while ((n=fis.read(buf))>0)
        baos.write(buf, 0, n);
catch (IOException x) {
    ...
}
byte result[]=baos.toByteArray();

*OR*, if you have access to the File (which you should, as you have a
FileInputStream)

File f=...;
FileInputStream fis=new FileInputStream(f);
long len=fis.length();
byte result[]=new byte[len];
long i=0, n;

try {
    while (i<len) {
        n=fis.read(result, i, len-i);
        if (n<0) break;
        i+=n;
    }
} catch (Exception x) {...}

if (i<len) { ? }
Technical Details
Message-ID: <3abb0e49_1@dnews>
Path: arc1-ca.pugleaf.net!supernews.google.com!sn-xit-03!supernews.com!logbridge.uoregon.edu!news.maxwell.syr.edu!newsfeed.wirehub.nl!PeerFeed.KWeb.on.ca!dnews!212.109.9.42
References: <3AB7BC0C.60473976@borland.com>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f74b3,2ea00c6aa2f0fa5a
X-Google-Attributes: gidf74b3,public
X-Google-ArrivalTime: 2001-03-23 04:10:05 PST
From: "Johan Forsberg" <jfo@SPAMalcesysIS.seBAD>
Newsgroups: borland.public.jbuilder.java.language
References: <3AB7BC0C.60473976@borland.com>
Subject: Re: How can I read in file into a byte array?
Date: Fri, 23 Mar 2001 09:51:51 +0100
Lines: 47
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 5.50.4133.2400
X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4133.2400
NNTP-Posting-Host: 212.109.9.42
Message-ID: <3abb0e49_1@dnews>
X-Trace: 23 Mar 2001 00:50:17 -0800, 212.109.9.42
Path: arc1-ca.pugleaf.net!supernews.google.com!sn-xit-03!supernews.com!logbridge.uoregon.edu!news.maxwell.syr.edu!newsfeed.wirehub.nl!PeerFeed.KWeb.on.ca!dnews!212.109.9.42