Java编写去除代码文件中的注释以及空格、换行,并写入目标文件中:
public static void pretreatment(String fileName, String targetFileName) throws IOException {
int dquo = 34;
int squo = 39;
int[] annoleft = { 47, 42 };
int[] annoright = { 42, 47 };
int[] doublefslash = { 47, 47 };
int[] enterline = { 13, 10 };
File sourceFile = new File(fileName);
if (!sourceFile.exists()) {
return;
}
FileInputStream fis = new FileInputStream(sourceFile);
File targetFile = new File(targetFileName);
RandomAccessFile fos = new RandomAccessFile(targetFile, "rw");
int pre = 0;
int current = 0;
int flag = -1;
/*
* flag:
* -1: default;
* 0: in double fslash;
* 1: in annotation left and annotation right;
* 3: in single quotation;
* 4: in double quotation;
* */
while((current = fis.read())!=-1) {
switch(flag){
case 0:{
//End of this case.
if ((pre == enterline[0] && current == enterline[1])) {flag = -1;}
}
break;
case 1:{ //annotation left and annotation right
if ((pre == annoright[0] && current == annoright[1])) {flag = -1;}
}
break;
case 3:{ //single quotation
if (current == squo) {flag = -1;}
// Don't have to delete space in quotation.
if (current!=9 && current!=10 && current!=13) {
fos.write((char)current);
}
}
break;
case 4:{ //double quotation
if (current == dquo) {flag = -1;}
// Don't have to delete space in quotation.
if (current!=9 && current!=10 && current!=13) {
fos.write((char)current);
}
}
break;
default:{
//Default characristics, flag==-1.
//Judge the different 4 cases.
if (current!=9 && current!=10 && current!=32 && current!=13) {
fos.write((char)current);
}
if (pre == doublefslash[0] && current == doublefslash[1]) {
// Found a double fslash.
flag = 0;
fos.seek(fos.getFilePointer()-2);
}else if (pre == annoleft[0] && current == annoleft[1]) {
// Found a annotation left.
flag = 1;
fos.seek(fos.getFilePointer()-2);
}else if (current == squo) {
// Found a single quotation.
flag = 3;
}else if (current == dquo) {
// Found a double quotation.
flag = 4;
}
}
break;
}
pre = current;
}// End of while
fis.close();
fos.close();
}
测试代码:
public static void main(String[] args) throws IOException {
System.out.println("App starts...");
pretreatment("./test1.txt", "./test2.txt");
}
test1.txt:
#include <stdio.h>
int main(){
int a = 0;
printf("%d",a);
return 0;
}
/*annnnnnnnnnnnnnn*/
//dsadsad
运行结果:
test2.txt:
#include<stdio.h>intmain(){inta=0;printf("%d",a);return0;}