Skip to content

Instantly share code, notes, and snippets.

@GUIpsp
Created November 28, 2013 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GUIpsp/7698441 to your computer and use it in GitHub Desktop.
Save GUIpsp/7698441 to your computer and use it in GitHub Desktop.
Java commentkiller
package net.guipsp.commentkiller;
import java.io.*;
public class Main {
public static final void main(String[] args) {
try {
stripComments(new FileReader("in.java"), new FileWriter("out.java"));
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
private static final void stripComments(Reader in, Writer out) throws IOException {
//by GUIpsp, if you could keep this comment in that's be great, if not that's great too.
//License: CC0
boolean inComment = false;
boolean inString = false;
char c;
int ci;
while ((ci = in.read()) != -1) {
c = (char) ci;
switch (c) {
case '\\': {
out.write(c);
out.write(in.read());//Eat for escaped "
break;
}
case '\"': {
if (!inComment) {
out.write(c);
inString = !inString;
}
break;
}
case '\'': {
if (!inComment) {
out.write(c);
out.write(in.read());
out.write(in.read());
}
break;
}
case '*': {
char c2 = (char) in.read();
if (inComment && c2 == '/') {
inComment = false;
out.write(' ');//Allows int x = 3; int y = -/**/-x; to work
} else {
out.write(c);
out.write(c2);
}
break;
}
case '/': {
if (!inString) {
char c2 = (char) in.read();
switch (c2) {
case '/':
char c3 = 0;
while (c3 != '\n' && c3 != '\r') {
c3 = (char) in.read();
}
out.write(c3);//write newline
break;
case '*':
inComment = true;
break;
default:
out.write(c);
out.write(c2);
break;
}
} else {
out.write(c);
}
break;
}
default: {
if (!inComment) {
out.write(c);
}
break;
}
}
}
out.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment