FileInputStream trouble

Hello,

I'm working on a program that reads in files then transfers them across a network to be stored on a server. The program works fine but the reading in of new files on the client side is extremely slow. Heres a snippet of the file input stream.

in = new FileInputStream(text1.getText());

int c;

while ((c = in.read()) != -1) {

dataout = dataout + c;

}

Is it because im reading the bytes into a string or is there a better way of doing this entirely? I've used fileinputstreams in programs in the past but I never remember it being this slow.

Thanks alot

[616 byte] By [Phillsa] at [2007-11-27 0:52:53]
# 1
1. read in a block of bytes at once instead of just 1 byte.2. Wrap your input stream in a BufferedReader.
bschauwejavaa at 2007-7-11 23:24:33 > top of Java-index,Java Essentials,Java Programming...
# 2
Agreed, use BufferedReader and readLine(), or perhaps the newer Scanner class - in which case you can read in the entire file in one shot. Have a look ... [url http://java.sun.com/developer/JDCTechTips/2004/tt1201.html#1] SCANNING TEXT WITH JAVA.UTIL.SCANNER[/url]
abillconsla at 2007-7-11 23:24:33 > top of Java-index,Java Essentials,Java Programming...
# 3

Hello,

Thanks for both the comments i'm now using a buffered and im going to try to read in a block of bytes. Isn't the bufferedreader only for characters or can it be used to read bytes in aswell? Also i've looked at the scanner class but that seems only for characters aswell, am i missing something or is there another class I can use. All I want to do is input the bytes of a file without it taking so long.

Thanks again

Phillsa at 2007-7-11 23:24:33 > top of Java-index,Java Essentials,Java Programming...
# 4

> Isn't the bufferedreader only for characters or can

> it be used to read bytes in aswell?

Yes, it is. You explicitly said you were reading the data into a String, so it would be reasonable to use a Reader in this case. But if your data is not text, then building a String out of the bytes is a bad idea, as you are going to run into encoding problems when you write that String out.

And repeatedly appending to a string like that is a known performance problem.

Furthermore if you are just copying data from a file to somewhere else, accumulating the entire file into memory is also a bad idea. Just read the bytes from the file and write them to the somewhere else. Use a BufferedInputStream if you like.

DrClapa at 2007-7-11 23:24:33 > top of Java-index,Java Essentials,Java Programming...