473,386 Members | 1,738 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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 18755
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
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
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
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
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
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
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
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
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
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
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.