Change multiple words in a file using Java
Contents of script.txt file
MYWORLD 543x_family COM1
ERASE_RACE
TR_PASSWORD
//BOSE
TP_DATA_LOCK test.txt
LMN 5C00 1010 982B
Change the words COM1 to COM5 and test.txt to mytext.txt.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class ReplaceWords
{
private static StringBuffer myStrArray = new StringBuffer();
//Stringbuffer can be used to append strings
private static String newStrArray[] = new String[6];//used to hold the strings
public static void main(String[] args)
{
readFile();
}
private static void readFile()
{
String next;
int i = 0;
FileInputStream fstream = null;
try
{
fstream = new FileInputStream("script.txt");
}
catch (FileNotFoundException ex)
{
System.out.println("FileNotfound:-" + ex);
}
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine, oldtext = null;
String newtext = null;
try
{
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
oldtext += strLine + "\r\n";
//Tokenizes the current line read with space delimiter
StringTokenizer tz = new StringTokenizer(strLine, " ");
while (tz.hasMoreTokens())
{
next = tz.nextToken();
//if word contains the text 'COM',COM5 is appended instead of 'COM1'
if (next.contains("COM"))
{
myStrArray.append("COM5 ");
//appends COM5 instead of COM1
}
//appends space is space is encountered
else if (next.contains(" "))
{
myStrArray.append(" ");
}
//if word contains the text '.txt',mytext.txt is appended instead of test.txt
else if (next.contains(".txt"))
{
myStrArray.append("mytext.txt ");
}
else
{
myStrArray.append(next + " ");
}
}
newtext = myStrArray.toString();
newStrArray[i] = newtext;
i ++;
myStrArray = null;
myStrArray = new StringBuffer();
oldtext = null;
}
in.close();
writeToFile();
}
catch (IOException ex)
{
System.out.println("IO Exception:-" + ex);
}
}
//Writes string to file
private static void writeToFile()
{
FileWriter writer = null;
try
{
writer = new FileWriter("script.txt");
//Iterates through the string buffer
for (int j = 0; j < newStrArray.length; j ++)
{
String strData = newStrArray[j];
writer.write(strData);
//writes new line to file after every line
writer.write("\r\n");
}
writer.close();
}
catch (IOException ex)
{
System.out.println("IOException in writeToFile:-"+ex);
}
finally
{
try
{
writer.close();
}
catch (IOException ex)
{
System.out.println("Exception in closing writer:-"+ex);
}
}
}
}
Script.txt file will output the following
MYWORLD 543x_family COM5
ERASE_RACE
TR_PASSWORD
//BOSE
TP_DATA_LOCK mytext.txt
LMN 5C00 1010 982B
No comments:
Post a Comment
Thanks for visiting my Blog....Ur comments n suggestions are most valuable for me...Thanks