Re: file I/O question
- From: Jan Thomä <kork@xxxxxxxxxxxxxx>
- Date: Sun, 05 Jun 2005 23:59:54 +0200
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
.
- Prev by Date: Re: enums
- Next by Date: File not found
- Previous by thread: Re: enums
- Next by thread: File not found
- Index(es):
Relevant Pages
|
|