Minifying JavaScript Files with Java: An Efficient Approach for Code Optimization

The Java code provided facilitates the conversion of a JavaScript file to a minified JavaScript file. Importantly, the original JavaScript file remains unchanged, and a copy of the JavaScript file is created with the ".min.js" extension. This process ensures that the original file is preserved while a minified version is generated for optimization purposes.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class JSMinimizer {


    public static void main(String args[]) {
		    //minify all javascript in selected directory
        File sourceDir = new File("/dirpathofyourjavascript");


        for (File f : sourceDir.listFiles()) {
            if (f.isFile() && f.getName().contains("_min.js")) {
                System.out.println("Deleting: " + f);
                f.delete();
            }
        }


        for (File f : sourceDir.listFiles()) {
            if (f.isFile() && f.getName().endsWith(".js")) {
                minimizeJS(f);
            }
        }
    	/*
			//For converting single javascript file to be minified
			File f = new File("/dirpath/forceteach_some_function.js");
    	minimizeJS(f);*/
    }


    public static void minimizeJS(File f) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(f));
            StringBuilder minifiedContent = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.replaceAll("//.*", "").replaceAll("/\\*.*?\\*/", "");
                if (!line.trim().isEmpty()) {  // Only add non-empty lines
                    minifiedContent.append(line.trim());
                }
            }
            reader.close();
            String minifiedFileName = f.getName().replace(".js", "_min.js");
            File minifiedFile = new File(f.getParentFile(), minifiedFileName);
            FileWriter writer = new FileWriter(minifiedFile);
            writer.write(minifiedContent.toString());
            writer.close();
            System.out.println("Minified file created: " + minifiedFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}


Minify js file, convert to minified

Last update on Aug 05, 2024

Tags: java,javascript,convert,minified,minify,minifying

Back to Posts

Comments

No comments yet.

ForceTeach Corporation 2024