本帖最后由 Mrng8888 于 2012-7-25 00:14 编辑
- package test1;
- import java.io.*;
- import java.util.*;
- public class MyBufferedReader {
- private Reader r;
- public MyBufferedReader(Reader r) {
- this.r = r;
- }
- private String readLine(StringBuilder sb1) throws IOException {
- StringBuilder sb2 = new StringBuilder();
- int ch;
- while ((ch = r.read()) != -1) {
- if (ch == '\r') {
- continue;
- }
- if (ch == '\n') {
- return sb2.insert(0, sb1).toString();
- } else {
- sb2.append((char) ch);
- }
- }
- if (sb2.length() != 0) {
- return sb2.insert(0, sb1).toString();
- }
- return null;
- }
- // 读取一行,带行号功能,起始行号有用户指定
- @SuppressWarnings("resource")
- public String readLine(int lineNum) throws IOException {
- StringBuilder sb = new StringBuilder();
- Formatter formatter = new Formatter(sb);
- //***********************************问题***************************************************
- //主要是这里,怎么能把行号的位数不写死,比如文件有20行,这里就是%2d,如果是380行,就是%3d,依次类推
- formatter.format("%3d: ", lineNum);
- return readLine(sb);
- }
- // 读取一行
- public String readLine() throws IOException {
- return readLine(new StringBuilder());
- }
- public void myClose() throws IOException {
- r.close();
- }
- }
复制代码 |
|