傻了,很久不写java,感觉都不会了帮忙看看吧
我想把jQuery源码中的tab换成空格,顺手写了下,结果文件只有一半
但是那句System.....确实打印到了最后一行怎么回事?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;public class ReplaceTab2Space {

public static void main(String[] args){ try {
replace(
new File("E:/code2/test/other/js/jquery-1.4.3.js"),
new File("G:/abc/test.js"),
4 );
} catch (Exception e) {
e.printStackTrace();
}

}

/**
 * 替换文件中的Tab成空格
 * @param from  待替换的文件
 * @param to  替换后的文件
 * @param spaceSize  一个Tab替换成的空格数
 * @throws Exception 
 */
public static void replace(File from, File to, int spaceSize) throws Exception{
if(!to.exists()){
File f = to.getParentFile();
f.mkdirs();
to.createNewFile();
}else{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
to.renameTo(new File(to.getPath()+".bak_"+sdf.format(new Date())));
to.delete();
replace(from,to,spaceSize);
return;
}

StringBuilder sb = new StringBuilder(32);
for(int i=0; i<spaceSize; ++i){
sb.append(" ");
}

FileInputStream fis = new FileInputStream(from);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));

PrintWriter pw = new PrintWriter(to);

for(String s=null; (s=br.readLine())!=null; ){
s = s.replaceAll("\t", sb.toString());
System.out.println(s);  //打印到文件尾部
pw.println(s);
}

}}

解决方案 »

  1.   

    s = s.replaceAll("\t", sb.toString()); 改成s = s.replaceAll("\\t", sb.toString()); 试试
      

  2.   

    public static void main(String[] args) {
    String a = "a a s s s fdasfdasf";
    System.out.println(a);
    System.out.println(a.replaceAll("\t", ","));
    }
    输出结果:
    a a s s s fdasfdasf
    a,a,s,s,s,fdasfdasf
    说明 \t 是对的……
      

  3.   


    PrintWriter pw = new PrintWriter(new FileOutputStream(to),true);郁闷结贴了,分给你了~~