一个Java读取文件的例子
 
目标:写一个Java类,读取自己,并按照原来的格式输出到控制台。
 
源代码:
TestFile.java
package com.topsoft.icisrpt.domain._05_qd.entity;

import java.io.*;

/**
* Created by IntelliJ IDEA.
* File: TestFile.java
* User: leizhimin
* Date: 2008-1-28 16:56:21
*/

public class TestFile {
     public static void main(String args[]) throws IOException {
        File f = new File( "D:\\TestFile.java");
        LineNumberReader lineNumberReader = new LineNumberReader(
                 new FileReader(f));

        StringBuffer sb = new StringBuffer();
        String lineStr = lineNumberReader.readLine();
         while (lineStr != null) {
            sb.append(lineStr).append( "\n");
            lineStr = lineNumberReader.readLine();
        }
        System.out.println(sb.toString());
    }
}
 
 
控制台输出:
package com.topsoft.icisrpt.domain._05_qd.entity;

import java.io.*;

/**
* Created by IntelliJ IDEA.
* File: TestFile.java
* User: leizhimin
* Date: 2008-1-28 16:56:21
*/
public class TestFile {
    public static void main(String args[]) throws IOException {
        File f = new File("D:\\TestFile.java");
        LineNumberReader lineNumberReader = new LineNumberReader(
                new FileReader(f));

        StringBuffer sb = new StringBuffer();
        String lineStr = lineNumberReader.readLine();
        while (lineStr != null) {
            sb.append(lineStr).append("\n");
            lineStr = lineNumberReader.readLine();
        }
        System.out.println(sb.toString());
    }
}
 
呵呵,这是个测试例子,完成了。