Re: file I/O question



Hi,

the code is somewhat inefficient, since you create a ton of arrays and
string objects. It would be better just to create a maybe 64k array, read
it in and thats it. Oh and use a streamreader for the conversion of bytes
to chars. something lieke

int n =0;
char[] chars = new char[64000];

FileInputStream fis = new FileInputStream("README.TXT");
InputStreamReader reader = new InputStreamReader( fis );
StringBuffer buf = new StringBuffer();
while( (n = reader.read( chars, 0, chars.length )) != -1 ) {
buf.append( chars, 0, n ); // put into buffer
}
reader.close();
System.out.println( buf.toString() );

That way you just have one char array and reuse it. Also you dont produce a
ton of temporary string objects.

Best regards,
Jan

slurper wrote:

> try {
>
> FileInputStream fis = new FileInputStream("README.TXT");
> int n;
> while ((n = fis.available()) > 0) {
> byte[] b = new byte[n];
> int result = fis.read(b);
> if (result == -1) break;
> String s = new String(b);
> System.out.print(s); }
> // End while
> }
> // End try catch (IOException e) {System.err.println(e);}
> System.out.println();
>
> i wonder if this code snippet is correct. I think it is possible that not
> all content of README.TXT will be printed.
> the loop will run as long as there are bytes available without blocking
> the program. but will there be bytes available after opening the file? the
> program needs to block immediately waiting for I/O, or do i see this
> wrong?
>
> tx

--
______________________________________
insOMnia - We never sleep....
http://www.insomnia-hq.de
.



Relevant Pages

  • Re: Cloning and Distinct Copies of Objects
    ... of the String objects those references point to. ... Here's the original array, before anybody edits anything: ... Now edit the new array, changing one of its references to point ...
    (comp.lang.java.help)
  • Re: html table dynamic dimensions that track a for loop
    ... don't know what particular poster you are referring to. ... AAA = new Array( ... Do you really understand how many String objects are created in the process? ... unless the language implementation is really very b0rken. ...
    (comp.lang.javascript)
  • Re: Sorting an Array of String Objects
    ... TheVooDooChild wrote: ... > I have a small array of String objects that I need to sort ...
    (comp.lang.java.programmer)
  • Re: This must be easy... help?
    ... i'll even make it an espresso! ... split is a function of String objects, which turns it into an array. ... Now a is an array. ...
    (comp.lang.javascript)