把一个file对象的内容带上行号复制到另一个file对象(java)

来源:互联网 发布:audition mac无法验证 编辑:程序博客网 时间:2024/06/15 11:15
import java.io.*;public class CopyFileAddLineNumber {    public static void main (String[] args) {        String infname = "CopyFileAddLineNumber.java";        String outfname = "CopyFileAddLineNumber.txt";        if( args.length >= 1 ) infname = args[0];        if( args.length >= 2 ) outfname = args[1];        try {            File fin = new File(infname);            File fout = new File(outfname);            BufferedReader in = new BufferedReader(new FileReader(fin));            PrintWriter out  = new PrintWriter(new FileWriter(fout));            int cnt = 0;    // 行号            String s = in.readLine();            while ( s != null ) {                cnt ++;                 s = deleteComments(s);                      //去掉以//开始的注释                out.println(cnt + ": \t" + s );             //写出                s = in.readLine();                          //读入            }                       in.close();             // 关闭缓冲读入流及文件读入流的连接.            out.close();        } catch (FileNotFoundException e1) {            System.err.println("File not found!" );        } catch (IOException e2) {            e2.printStackTrace();        }    }    static String deleteComments( String s ) //去掉以//开始的注释    {        if( s==null ) return s;        int pos = s.indexOf( "//" );        if( pos<0 ) return s;        return s.substring( 0, pos );    }}

java.nio.file.Files中有readAllLines()方法

import java.nio.file.*;import java.nio.charset.*;import java.util.List;class ReadAllLines{    public static void main(String[] args) throws java.io.IOException    {        String filePath = "d:\\javaExample\\ch09\\ReadAllLines.java";        List<String> lines = Files.readAllLines(            Paths.get(filePath),              Charset.forName("utf8") //or Charset.defaultCharset()        );        for(String s : lines ) System.out.println(s);    }}

若对字节流 字符流 节点流 过滤流概念不清楚可查看前一篇博客~

阅读全文
0 0