import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class Readjavafile {
/*获取当前项目根路径
* */
public static final String rootpath = System.getProperty("user.dir");
public static List<String> getfilepath(){
List<String> li=new ArrayList<String>();
File[] list = new File(rootpath).listFiles();
for(File file : list)
{
if(file.isFile())
{
if (file.getName().endsWith(".java")) {
// 就输出该文件的绝对路径
String st=file.getAbsolutePath();
System.out.println(st);
li.add(st);
}
}
}
return li;
}
public static void inputtxt() throws IOException{
String fileName = rootpath+"\\java.txt";
File f=new File(fileName);
OutputStream out = new FileOutputStream(f,true);//true表示是在文件后面追加内容,而不是覆盖。默认的是覆盖
List<String> li=getfilepath();
for(String st :li){
File file = new File(st);
Long fileLength = file.length();
byte[] fileContext = new byte[fileLength.intValue()];
FileInputStream in = new FileInputStream(st);
in.read(fileContext);
String str = new String(fileContext);
str = str.replaceAll("\\/\\*[\\w\\W]*?\\*\\/|\\/\\/.*", "");/* "\\/\\*[\\s\\S]*\\*\\/|\\/\\/.*" 两个都能除去注释*/
str = str.replaceAll("\r\n *\r\n", "\r\n");
str = str.replaceAll("\r\n *\r\n", "\r\n");
str = str.replaceAll("\r\n\r\n", "\r\n");
str=str+"\r\n";
byte[] bs = str.getBytes();
for(int i = 0 ; i < bs.length ; i++){
out.write(bs[i]);
}
}
out.close();
}
public static void main(String[] args) throws IOException{
inputtxt();
System.out.println("完成!");
}
}
复制java代码并除去空行和注释
最新推荐文章于 2024-10-04 15:11:36 发布