I have the following text file (not a java file)
/*START OF CHANGES TO CODE*/
public class method1 {
public static int addTwoNumbers(int one, int two){
return one+two;
}
public static void main (String[] args){
int total = addTwoNumbers(1, 3);
System.out.println(total);
}
}
/*END OF CHANGES TO CODE*/
I am trying to use the following code to read the file
String editedSection = null;
boolean containSection = false;
Scanner in = new Scanner(new FileReader(directoryToAddFile));
while(in.hasNextLine()) {
if(in.nextLine().contains("/*START OF CHANGES TO CODE*/")) {
containSection = true;
editedSection = in.nextLine().toString();
} else if (containSection == true) {
editedSection = editedSection+in.nextLine().toString();
} else if (in.nextLine().contains("/*END OF CHANGES TO CODE*/")) {
containSection = false;
editedSection = in.nextLine().toString();
}
in.nextLine();
}
So basically what i want it to do is read a file till it see’s /*START OF CHANGES TO CODE*/, then start adding every line after this to a string till it reaches /*END OD CHANGES TO CODE*/. But when it is reading lines it ignores some lines and parts of others. Does anyone know how to do this?
You’re calling
in.nextLine()lots of times within thatwhileloop. That sounds like a really bad idea to me. How many times it will execute on each iteration will depend on which bits it went into… nasty.I suggest you use
That way you won’t accidentally skip lines by reading them just for checking purposes.