473,498 Members | 1,936 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Regex on whole (large) text file

Hi,

I'm sorry if these questions are trivial, but I've searched the net and
haven't had any luck finding the information I need.

I need to perform some regular expression search and replace on a large
text file. The patterns I need to match are multi-line, so I can't do it
one line at a time. Instead I currently read in the entire text file in
a string using the code below.

File fin = new File("input.txt");
FileInputStream fis = new FileInputStream(fin);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine = null;
String theText = "";
while((aLine = in.readLine()) != null) {
theText = theText + aLine + "\n";
}

The problem with this is that the first couple of thousand lines read in
very fast, but it gets slower and slower, and as we approach line 4000
it gets really slow per line.

Is there a better way to read in an entire text file into a string?

Is storing the entire text file in a string a bad idea? And if so, what
are the alternatives?

Is it possible to perform multiple-line regular expressions on a text
file without loading the whole text file into memory?

Thanks in advance,
Rune
Jul 17 '05 #1
8 18767
Rune Johansen wrote:
Hi,

I'm sorry if these questions are trivial, but I've searched the net and
haven't had any luck finding the information I need.

I need to perform some regular expression search and replace on a large
text file. The patterns I need to match are multi-line, so I can't do it
one line at a time. Instead I currently read in the entire text file in
a string using the code below.

File fin = new File("input.txt");
FileInputStream fis = new FileInputStream(fin);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine = null;
String theText = "";
while((aLine = in.readLine()) != null) {
theText = theText + aLine + "\n";
}

The problem with this is that the first couple of thousand lines read in
very fast, but it gets slower and slower, and as we approach line 4000
it gets really slow per line.

Is there a better way to read in an entire text file into a string?


Absolutely. Instead of using + to concatenate strings, you should use a
StringBuffer and convert to a String at the end:

File fin = new File("input.txt");
FileInputStream fis = new FileInputStream(fin);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine = null;
StringBuffer theText = new StringBuffer((int)fin.length());
while((aLine = in.readLine()) != null)
{
// Question: Why are you converting all the line breaks
// to \n?
theText.append(aLine).append("\n");
}

Ray

--
XML is the programmer's duct tape.
Jul 17 '05 #2
Raymond DeCampo wrote:
Absolutely. Instead of using + to concatenate strings, you should
use a StringBuffer and convert to a String at the end
Thanks a lot! This indeed solves the problem.
Question: Why are you converting all the line breaks to \n?


How do I preserve the line breaks? Before I added the \n, the whole
string, when written to a file, was in a single line.

Rune
--
3D images and anims, include files, tutorials and more:
rune|vision: http://runevision.com **updated Apr 27**
POV-Ray Ring: http://webring.povray.co.uk
Jul 17 '05 #3

"Rune Johansen" <rune[insert_current_year_here]@runevision.com> wrote in
message news:Ts********************@news000.worldonline.dk ...
Raymond DeCampo wrote:
Absolutely. Instead of using + to concatenate strings, you should
use a StringBuffer and convert to a String at the end


Thanks a lot! This indeed solves the problem.
Question: Why are you converting all the line breaks to \n?


How do I preserve the line breaks? Before I added the \n, the whole
string, when written to a file, was in a single line.

Rune
--
3D images and anims, include files, tutorials and more:
rune|vision: http://runevision.com **updated Apr 27**
POV-Ray Ring: http://webring.povray.co.uk


Read characters (or bytes) instead of lines. Reading lines is useless unless
you want to process individual lines.

Silvio Bierman
Jul 17 '05 #4
Silvio Bierman wrote:
Read characters (or bytes) instead of lines. Reading lines
is useless unless you want to process individual lines.


Okay, I now read characters instead, using the following method:

public static String readTextFile(String filename) {
try {
File fin = new File(filename);
FileInputStream fis = new FileInputStream(fin);
BufferedReader in = new BufferedReader(new
InputStreamReader(fis));
char[] chrArr = new char[(int)fin.length()];
while(in.ready()==false) {}
in.read(chrArr);
in.close();
return new String(chrArr);
}
catch (FileNotFoundException e) { return ""; }
catch (IOException e) { return ""; }
}

Except for the poor exception handling, is there anything obvious that
could be improved here?

Rune
Jul 17 '05 #5

"Rune Johansen" <rune[insert_current_year_here]@runevision.com> wrote in
message news:65********************@news000.worldonline.dk ...
Silvio Bierman wrote:
Read characters (or bytes) instead of lines. Reading lines
is useless unless you want to process individual lines.


Okay, I now read characters instead, using the following method:

public static String readTextFile(String filename) {
try {
File fin = new File(filename);
FileInputStream fis = new FileInputStream(fin);
BufferedReader in = new BufferedReader(new
InputStreamReader(fis));
char[] chrArr = new char[(int)fin.length()];
while(in.ready()==false) {}
in.read(chrArr);
in.close();
return new String(chrArr);
}
catch (FileNotFoundException e) { return ""; }
catch (IOException e) { return ""; }
}

Except for the poor exception handling, is there anything obvious that
could be improved here?

Rune


Rune,

You could drop the BufferedReader and read from the InputStreamReader
directly. This will be somewhat faster. In cases where you would be
processing the file as a character stream you should use the BufferedRe\ader
though.

Silvio Bierman
Jul 17 '05 #6
Silvio Bierman wrote:
"Rune Johansen" <rune[insert_current_year_here]@runevision.com> wrote in
message news:65********************@news000.worldonline.dk ...
Silvio Bierman wrote:
Read characters (or bytes) instead of lines. Reading lines
is useless unless you want to process individual lines.


Okay, I now read characters instead, using the following method:

public static String readTextFile(String filename) {
try {
File fin = new File(filename);
FileInputStream fis = new FileInputStream(fin);
BufferedReader in = new BufferedReader(new
InputStreamReader(fis));
char[] chrArr = new char[(int)fin.length()];
while(in.ready()==false) {}
in.read(chrArr);
in.close();
return new String(chrArr);
}
catch (FileNotFoundException e) { return ""; }
catch (IOException e) { return ""; }
}

Except for the poor exception handling, is there anything obvious that
could be improved here?

Rune

Rune,

You could drop the BufferedReader and read from the InputStreamReader
directly. This will be somewhat faster. In cases where you would be
processing the file as a character stream you should use the BufferedRe\ader
though.

Silvio Bierman


I definitely disagree with that. My understanding is that
FileInputStream, FileOutputStream, FileReader and FileWriter are not
buffered and will go to the file system for every byte/character. So
they should almost always be wrapped with the appropriate buffered stream.

I would however, ditch the FileInputStream/InputStreamReader combination
in favor of FileReader.

The other potential issue is that InputStream.in() is not guaranteed to
fill the array (although in practice I think it usually does). So the
paranoid way to do this would be in a loop that ensures that all the
desired characters are read.

Finally, I don't think the while loop you have adds any value and will
just eat CPU cycles if it does anything.

And speaking of finally, you should use a finally clause to close your
streams.

Ray

--
XML is the programmer's duct tape.
Jul 17 '05 #7

"Raymond DeCampo" <rd******@spam.twcny.spam.rr.spam.com.spam> wrote in
message news:52********************@twister.nyroc.rr.com.. .
Silvio Bierman wrote:
"Rune Johansen" <rune[insert_current_year_here]@runevision.com> wrote in
message news:65********************@news000.worldonline.dk ...
Silvio Bierman wrote:

Read characters (or bytes) instead of lines. Reading lines
is useless unless you want to process individual lines.

Okay, I now read characters instead, using the following method:

public static String readTextFile(String filename) {
try {
File fin = new File(filename);
FileInputStream fis = new FileInputStream(fin);
BufferedReader in = new BufferedReader(new
InputStreamReader(fis));
char[] chrArr = new char[(int)fin.length()];
while(in.ready()==false) {}
in.read(chrArr);
in.close();
return new String(chrArr);
}
catch (FileNotFoundException e) { return ""; }
catch (IOException e) { return ""; }
}

Except for the poor exception handling, is there anything obvious that
could be improved here?

Rune

Rune,

You could drop the BufferedReader and read from the InputStreamReader
directly. This will be somewhat faster. In cases where you would be
processing the file as a character stream you should use the BufferedRe\ader though.

Silvio Bierman


I definitely disagree with that. My understanding is that
FileInputStream, FileOutputStream, FileReader and FileWriter are not
buffered and will go to the file system for every byte/character. So
they should almost always be wrapped with the appropriate buffered stream.

I would however, ditch the FileInputStream/InputStreamReader combination
in favor of FileReader.

The other potential issue is that InputStream.in() is not guaranteed to
fill the array (although in practice I think it usually does). So the
paranoid way to do this would be in a loop that ensures that all the
desired characters are read.

Finally, I don't think the while loop you have adds any value and will
just eat CPU cycles if it does anything.

And speaking of finally, you should use a finally clause to close your
streams.

Ray

--
XML is the programmer's duct tape.


Raymond,

The non-buffered streams and readers do not go to the filesystem for every
byte/character but for every read action instead. If you plan to read say 1M
bytes in a single read a plain stream will do a single filesystem level read
where a buffered reader will read multiple times its buffer size until the
1M bytes are read. If the raw variants where so dumb it would be impossible
for the buffered ones to use them efficiently.

As I said If you intend to read single (or very small counts of)
bytes/characters frequently the buffered variants will group the reads and
therefore give better performance.

It is a common misconception that you should always use buffered
streams/readers. If this where true the plain ones would have porobably been
left out of the API.

Regards,

Silvio Bierman
Jul 17 '05 #8
Silvio Bierman wrote:
"Raymond DeCampo" <rd******@spam.twcny.spam.rr.spam.com.spam> wrote in
message news:52********************@twister.nyroc.rr.com.. .
Silvio Bierman wrote:
Rune,

You could drop the BufferedReader and read from the InputStreamReader
directly. This will be somewhat faster. In cases where you would be
processing the file as a character stream you should use the
BufferedRe\ader
though.

Silvio Bierman


I definitely disagree with that. My understanding is that
FileInputStream, FileOutputStream, FileReader and FileWriter are not
buffered and will go to the file system for every byte/character. So
they should almost always be wrapped with the appropriate buffered stream.
Ray

--
XML is the programmer's duct tape.

Raymond,

The non-buffered streams and readers do not go to the filesystem for every
byte/character but for every read action instead. If you plan to read say 1M
bytes in a single read a plain stream will do a single filesystem level read
where a buffered reader will read multiple times its buffer size until the
1M bytes are read. If the raw variants where so dumb it would be impossible
for the buffered ones to use them efficiently.

As I said If you intend to read single (or very small counts of)
bytes/characters frequently the buffered variants will group the reads and
therefore give better performance.

It is a common misconception that you should always use buffered
streams/readers. If this where true the plain ones would have porobably been
left out of the API.

Regards,

Silvio Bierman


Hmm, that makes sense. Thanks for the clarification.

Ray

--
XML is the programmer's duct tape.
Jul 17 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2369
by: Alan Pretre | last post by:
Can anyone help me figure out a regex pattern for the following input example: xxx:a=b,c=d,yyy:e=f,zzz:www:g=h,i=j,l=m I would want four matches from this: 1. xxx a=b,c=d 2. yyy e=f 3....
2
3041
by: jimmyfishbean | last post by:
Hi, I am using VB6, SAX (implementing IVBSAXContentHandler). I need to extract binary encoded data (images) from large XML files and decode this data and generate the appropriate images onto...
7
5703
by: alphatan | last post by:
Is there relative source or document for this purpose? I've searched the index of "Mastering Regular Expression", but cannot get the useful information for C. Thanks in advanced. -- Learning...
1
3372
by: Mark | last post by:
Hi, I've seen some postings on this but not exactly relating to this posting. I'm reading in a large mail message as a string. In the string is an xml attachment that I need to parse out and...
8
1838
by: rjb | last post by:
Hi! Could somebody have a look and help me to optimize the code below. It may look like very bad way of coding, but this stuff is very, very new for me. I've included just few lines. Regex...
4
3583
by: shonend | last post by:
I am trying to extract the pattern like this : "SUB: some text LOT: one-word" Described, "SUB" and "LOT" are key words; I want those words, everything in between and one word following the...
4
1901
by: MooMaster | last post by:
I'm trying to develop a little script that does some string manipulation. I have some few hundred strings that currently look like this: cond(a,b,c) and I want them to look like this: ...
17
1967
by: garrickp | last post by:
While creating a log parser for fairly large logs, we have run into an issue where the time to process was relatively unacceptable (upwards of 5 minutes for 1-2 million lines of logs). In contrast,...
1
2707
by: =?Utf-8?B?QWxCcnVBbg==?= | last post by:
I have a regular expression for capturing all occurrences of words contained between {{ and }} in a file. My problem is I need to capture what is between those symbols. For instance, if I have...
0
7125
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7002
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7165
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6885
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
4908
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4588
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1417
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
656
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
290
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.