i want to search and replace strings present in a file (entire file)..
i have wirtten cod eto do this..
but it is not working as expected..
code is :
import java.io.*;
import java.util.*;
public class StringReplacer {
private String replaceString;
private String replacerString;
private String filePath;
public StringReplacer( String replaceString, String replacerString, String filePath)
{
this.replaceStr ing = replaceString;
this.replacerSt ring = replacerString;
this.filePath = filePath;
try
{
replace();
}
catch (Exception ex)
{
}
}
public StringReplacer( )
{
}
private void replace() throws Exception
{
//RandomAccessFil e raf=new RandomAccessFil e(filepath,"rwd ");
File file = new File(filePath);
if(!file.exists ())
{
System.out.prin tln("File doesnot exists");
return;
}
DataInputStream dis = new DataInputStream (new FileInputStream (file));
StringBuffer fileData = new StringBuffer("" );
String strTemp = "";
System.out.prin tln("before while");
while((strTemp = dis.readLine()) != null)
{
//String str=new String();
System.out.prin tln("inside while");
fileData.append (strTemp);
System.out.prin tln(strTemp);
}
System.out.prin tln("after while");
dis.close();
System.out.prin tln("before string tokenizer");
StringTokenizer stTemp = new StringTokenizer (fileData.toStr ing()," ",true);
System.out.prin tln(stTemp);
System.out.prin tln("after string tokenizer");
int tokens = stTemp.countTok ens();
if(tokens <= 1)
{
// No matches found for string to be replaces.
System.out.prin tln("No matches found for string to be replaced");
return;
}
fileData = new StringBuffer("" );
while(stTemp.ha sMoreTokens())
{
//fileData.append (stTemp.nextTok en());// + replacerString) ;
fileData.append (stTemp.nextTok en() + replacerString) ;
}
if(file.exists( ))
file.delete();
file = new File(filePath);
if(!file.exists ())
file.createNewF ile();
DataOutputStrea m dos = new DataOutputStrea m(new FileOutputStrea m(file));
dos.writeChars( fileData.toStri ng());
dos.flush();
dos.close();
}
}
when i run this ..
i am not getting expected out put..
please suggest me something
2 1539
i want to search and replace strings present in a file (entire file)..
i have wirtten cod eto do this..
but it is not working as expected..
code is :
import java.io.*;
import java.util.*;
public class StringReplacer {
private String replaceString;
private String replacerString;
private String filePath;
public StringReplacer( String replaceString, String replacerString, String filePath)
{
this.replaceStr ing = replaceString;
this.replacerSt ring = replacerString;
this.filePath = filePath;
try
{
replace();
}
catch (Exception ex)
{
}
}
public StringReplacer( )
{
}
private void replace() throws Exception
{
//RandomAccessFil e raf=new RandomAccessFil e(filepath,"rwd ");
File file = new File(filePath);
if(!file.exists ())
{
System.out.prin tln("File doesnot exists");
return;
}
DataInputStream dis = new DataInputStream (new FileInputStream (file));
StringBuffer fileData = new StringBuffer("" );
String strTemp = "";
System.out.prin tln("before while");
while((strTemp = dis.readLine()) != null)
{
//String str=new String();
System.out.prin tln("inside while");
fileData.append (strTemp);
System.out.prin tln(strTemp);
}
System.out.prin tln("after while");
dis.close();
System.out.prin tln("before string tokenizer");
StringTokenizer stTemp = new StringTokenizer (fileData.toStr ing()," ",true);
System.out.prin tln(stTemp);
System.out.prin tln("after string tokenizer");
int tokens = stTemp.countTok ens();
if(tokens <= 1)
{
// No matches found for string to be replaces.
System.out.prin tln("No matches found for string to be replaced");
return;
}
fileData = new StringBuffer("" );
while(stTemp.ha sMoreTokens())
{
//fileData.append (stTemp.nextTok en());// + replacerString) ;
fileData.append (stTemp.nextTok en() + replacerString) ;
}
if(file.exists( ))
file.delete();
file = new File(filePath);
if(!file.exists ())
file.createNewF ile();
DataOutputStrea m dos = new DataOutputStrea m(new FileOutputStrea m(file));
dos.writeChars( fileData.toStri ng());
dos.flush();
dos.close();
}
}
when i run this ..
i am not getting expected out put..
please suggest me something
I think you use the Java 1.3.
From Java 1.4 the String.replace method available.
I think you try to write code yourself.
Good Idea!
First get the total string in a String variable.
Then try my code..... -
String file_str = ......
-
if(file_str.indexOf(replaceString)!=-1){
-
StringBuffer temp_str = new StringBuffer(file_str);
-
boolean complete = false;
-
int start_pos;
-
while(!complete)
-
if((start_pos=temp_str.toString().indexOf(replaceString))!-=1) temp_str = temp_str.replace(start_pos,replace_str.length(),replacerString);
-
String replaced_str = temp_str.toString();
-
}
-
I think it will work.
Debasis Jana
JosAH 11,448
Recognized Expert MVP
Don't use DataStreams for text reading/writing purposes; use Readers and Writers
instead. They're made for that job.
kind regards,
Jos
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: beliavsky |
last post by:
The code
for text in open("file.txt","r"):
print text.replace("foo","bar")
replaces 'foo' with 'bar' in a file, but how do I avoid changing text
inside single or double quotes? For making changes to Python code, I
would also like to avoid changing text in comments, either the '#' or
'""" ... """' kind.
|
by: Epson Barnett |
last post by:
I'm working on learning .NET and I'm curious about the reason for
using static methods in some cases. Specifically, the string class has
a split and a join method, but only the join method is static.
Both methods return a new string which is based on another string. It
would seem that both should not be static.
string mystring = "one, two, three, four";
string newstring = mystring.Split(',');
|
by: Steve |
last post by:
Hi Guys,
I have a string which contains data elements separated by spaces. I also
have a function which returns the number of characters from the beginning of
the string for a given number of spaces. I am using a loop with strchr for
the number of spaces, and I was just wondering if there was a more efficient
(ie faster) way of achieving this. Any ideas please? Current function code
below:
int GetNewPosition(const std::string&...
|
by: tshad |
last post by:
Can you do a search for more that one string in another string?
Something like:
someString.IndexOf("something1","something2","something3",0)
or would you have to do something like:
if ((someString.IndexOf("something1",0) >= 0) ||
((someString.IndexOf("something2",0) >= 0) ||
|
by: Matt |
last post by:
string format formula to write a text file
below is not working for me
pos 1 to 10 name
pos 15 to 30 lastname
pos 45 to 75 job
Adam smith programmer
string fmt = "{1,10}{15-30}{45,75}" // is not working any help ?
| |
by: rsine |
last post by:
I have developed a program that sends a command through the serial port
to our business system and then reads from the buffer looking for a
number. Everything worked great on my WinXP system, but when I tried
the program on the Win98 system it will be running on, I get the
following error:
Cast from string "2076719" to type 'Long' is not valid
I am not sure why I only get this error on the Win98 system or how to go
about correcting...
|
by: April |
last post by:
Hope someone can help me
The SQL string i need to use does not work, Who can help me....
Thanks in advance
Dim strConn As String
Dim strSQL As String
|
by: Xcriber51 |
last post by:
Hi --
I'm not entirely familiar with the norms and standard libraries of
JavaScript so if the answer to this is yesterday's news, please ignore.
I'm trying to write a simple text formatting function to make headings
proper case -- i.e. first letter of words capitalized.
I first tried this...
|
by: coconet |
last post by:
I have a string like this
mystring = "color1:blue;color2:red";
I am tring to convert this into an IDictionary populated like this:
color1 blue
color2 red
My non-working syntax is
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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 then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |