Reputation: 1956
I need to do processes on a file ,first count the number of lines and compare with a value.
The next is one to read thru the file line by line and do validations.
if first one passes only i need to do second process.
I read the same file using FTP.
When i try to create a different input stream...ftp is busy reading the current file.
like this :
(is1 = ftp.getFile(feedFileName);)
below is the remaining :
InputStream is = null;
LineNumberReader lin = null;
LineNumberReader lin1 = null;
is = ftp.getFile(feedFileName);
lin = new LineNumberReader(new InputStreamReader(is));
so can i just use like below:
is1=is;
Will both streams be having the file contents from start to finish or the second object will become null as soon as the first stream object is read.
So is the only option left is to create a new ftp object to read a stream seperately ?
Upvotes: 2
Views: 532
Reputation: 1356
if you file is not big, you can save data to a String. liek:
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer))!=-1)
sb.append(buffer, 0, len);
String data = sb.toString();
then you can do further thing in the String like:
int lineNumber = data.split("\n").length;
Upvotes: 1
Reputation: 17769
After you are done with the LineNumberReader, close the InputStream is
. Then re-request the file from FTP, it will not be busy then anymore. You cannot 'just' read from the same InputStream, as that one is probably exhausted by the time the LineNumberReader is done. Furthermore, not all InputStreams support the mark()
and reset()
methods.
However I'd suggest that doing the second process only when the first one succeeds might not be the right way. As you're streaming the data anyways, why not stream it into a temporary data structure and then count the lines and then operate on the same data structure.
Upvotes: 2
Reputation: 604
It can, but you would need to "rewind" the InputStream. First you need to call mark() method on it, and then reset. Here are docs: http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#reset()
Upvotes: 4