1. import java.io.File;
  2. import java.io.IOException;
  3. import java.nio.file.Files;
  4. import java.nio.file.Paths;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.regex.Matcher;
  8. import java.util.regex.Pattern;
  9. public class CodeInstrumenter {
  10. public static void instrumentFile(String filePath, String instrumentationCode) throws IOException {
  11. // Read file contents
  12. String fileContent = new String(Files.readAllBytes(Paths.get(filePath)));
  13. // Construct the instrumentation code
  14. String instrumentation = instrumentationCode;
  15. // Find the end of the file (simple approach - might need refinement)
  16. int fileEnd = fileContent.length();
  17. // Inject instrumentation at the end of the file
  18. String instrumentedContent = fileContent + System.lineSeparator() + instrumentation;
  19. // Write the instrumented content back to the file
  20. Files.write(Paths.get(filePath), instrumentedContent.getBytes());
  21. }
  22. public static void main(String[] args) throws IOException {
  23. //Example Usage
  24. //Instrumentation code to be added to the end of the file
  25. String instrumentationCode = "System.out.println(\"File instrumented!\");";
  26. //File path to the legacy project file
  27. String filePath = "legacy_file.java";
  28. //Create a dummy file for testing
  29. File file = new File(filePath);
  30. if (!file.exists()) {
  31. try {
  32. Files.write(Paths.get(filePath), "public class LegacyClass {\n public void legacyMethod() {}\n}".getBytes());
  33. } catch (IOException e) {
  34. System.err.println("Error creating dummy file: " + e.getMessage());
  35. return;
  36. }
  37. }
  38. instrumentFile(filePath, instrumentationCode);
  39. }
  40. }

Add your comment