import java.io.*;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Try{
public static void main(String args[]){
String srcPath="C:\\Users\\Lenovo\\Desktop\\未命名1.cpp",dsPath="C:\\Users\\Lenovo\\Desktop\\1.cpp";
copyFile(srcPath,dsPath);
}
public static boolean isContainChinese(String str) {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
public static void copyFile(String srcPath,String dsPath){
try{
File infile =new File(srcPath);
File outfile =new File(dsPath);
BufferedReader bfr = new BufferedReader(new InputStreamReader(
new FileInputStream(infile), "GBK"));
BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outfile), "GBK"));
String context;
String pattern ="(\\s*[^\"]+//.*[^\"]*)";
int mark=0;
while((context=bfr.readLine())!=null){
if((Pattern.matches(pattern,context) && mark==1) &&!isContainChinese(context)){
context = context.replace("//","");
context =context.replace("\n"," ");
context =context.replace("\t"," ");
context = context.trim();
bfw.newLine();
bfw.newLine();
bfw.write(context);
mark=0;
}else if(Pattern.matches(pattern,context) && mark==0 &&!isContainChinese(context)) {
context = context.replace("//", "");
context = context.replace("\n", " ");
context = context.replace("\t", " ");
context = context.trim();
context = " "+context;
bfw.write(context);
mark = 0;
}else{
mark=1;
}
}
bfw.close();
bfr.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
java提取文件中//后的内容(包括中文)每行空行隔开
最新推荐文章于 2023-07-11 20:42:33 发布