在网上看demo,复制代码下来执行,通常前面的行数也一起复制了下来,今天想写一个小程序去除前面的行数,开始想用RandomAcessFile来实现的,遇到两个问题,1:writeChars()写出的字母是全角的,writeUTF()写出的字母前面竟然有一个$,不知道怎么搞的;2:由于去除前面的行数,因此write的字符数比read出来的字符数要少,write之后,发现最后的几个字符没有消失,我不知道用RandomAccessFile怎么删除指定的几个字母或者一行,想用""代替的,但想想这并不是一个完美方法,因此放弃,有知道的告诉我下这两个问题如何解决。
下面我是一个临时文件写的替代方案:
写出的代码缩进不好,可以soruce\format一下格式就好了。
下面我是一个临时文件写的替代方案:
public class TrimLineNumberInCode {
public static void trim(String filePath) throws IOException{
File oldFile = new File(filePath);
File newFile = File.createTempFile(oldFile.getName(), "tmp", oldFile.getParentFile());
Pattern pattern = Pattern.compile("(\\d{1,4}\\.?)(\\s+.+)");
Matcher m = null;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(oldFile)));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile)));
String str = null;
while((str=br.readLine())!=null){
m = pattern.matcher(str);
if(m.matches()){
bw.write(m.group(2));
}else{
bw.write(str);
}
bw.write(System.getProperty("line.separator"));
}
br.close();
bw.close();
oldFile.delete();
newFile.renameTo(oldFile);
}
public static void main(String...args){
try {
trim("test.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
写出的代码缩进不好,可以soruce\format一下格式就好了。