ChatGPT Wrote me Code Utility in Java and it was surprisingly good. I just needed to tell it very specifically what I needed in multiple aspects and multiple dimensions. It requires:
- The version of programming language. Probably it will going to be the same for – versions of frameworks, libraries, SDKs, operating systems and other items that add variations to the generated code
- Very well described – the business logic that is required. It understood and put in code all of it.
I needed an utility to:
- Parce all .java files in a directory
- Scan for String literals in it and replace their content with their lower case version and replace the interval with _.
The Result is the following:
package mypackage; import com.helger.commons.regex.RegExPattern; import java.io.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JavaStringTransformer { public static void main(String[] args) { // The directory containing the Java classes to analyze String directory = "mydir"; // The file extension of the Java classes to analyze String fileExtension = ".java"; // Loop through all files in the directory File folder = new File(directory); File[] files = folder.listFiles(); Pattern pattern = Pattern.compile("\"(.*?)\""); for (File file : files) { // Check if the file is a Java class if (file.isFile() && file.getName().endsWith(fileExtension)) { try { // Read the contents of the file into a string BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line).append("\n"); } String content = builder.toString(); reader.close(); Matcher matcher = pattern.matcher(content); while (matcher.find()) { // Get the original string literal String original = matcher.group(1); // Convert the string literal to lowercase and replace spaces with underscores String modified = original.toLowerCase().replace(' ', '_'); // Replace the original string literal with the modified version content = content.replace("\"" + original + "\"", "\"" + modified + "\""); } // Replace all string literals with lowercase and underscores // content = content.replaceAll("\"(.*?)\"", match -> { // String original = match.group(1); // String modified = original.toLowerCase().replace(' ', '_'); // return "\"" + modified + "\""; // }); // Write the modified content back to the file BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(content); writer.close(); // Print a message indicating the file was processed System.out.println("Processed file: " + file.getName()); } catch (IOException e) { // Handle any file IO errors System.err.println("Error processing file: " + file.getName()); e.printStackTrace(); } } } } }
It documented the code and put debug prints – for everything that it do. I’ll most likely try to use it again.