this is my class:
import java.io.*;
public class Test
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
BufferedReader br = new BufferedReader(new FileReader("file2.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"));
int i = 0;
String line;
while ((line = br.readLine()) != null) {
while(line.contains("^")) {
i ++;
line = line.replaceFirst("^", Integer.toString(i));
}
bw.write(line + "\n");
}
br.close();
bw.close();
}
}
the file2.txt and file.txt are exactly the same and I want to make the lines that look like
<wpt lat="26.381418638" lon="-80.101236298"><ele>0</ele><time> </time><name>Waypoint #^</name><desc> </desc></wpt>
to look like
<wpt lat="26.381418638" lon="-80.101236298"><ele>0</ele><time> </time><name>Waypoint #5</name><desc> </desc></wpt>
When I run it though, it goes on an infinite loop. Any advice will help. Thanks!
line = line.replaceFirst("^", Integer.toString(i));
replaceFirst
's first argument is a regular expression, and "^"
as a regular expression means "the start of the string". So this command just keeps prepending values to the start of the string, and never removes any circumflexes. Instead, you should write:
line = line.replaceFirst("\\^", Integer.toString(i));