readfilelines.java

来自「Java 入门书的源码」· Java 代码 · 共 34 行

JAVA
34
字号
//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.

/* Reads arg[1] lines from file args[0].
 */

import java.io.*;
public class ReadFileLines {
  public static void main(String [] args) {
    String line;
    int totalLines; // number of lines to read from the file 
    int count = 0;  // number of lines read so far 
    if (args.length != 2){
      System.out.print("Pass the file name and number of lines");
      System.out.println(" to read as program arguments");
      System.exit(1); 
    }
    try {
      totalLines = Integer.parseInt(args[1]);
    }catch(NumberFormatException e) {
      totalLines = 3;
    }  
    BufferedReader f; 
    try {
      f = new BufferedReader(new FileReader(args[0]));
      System.out.println("Opening " + args[0]);
      while((line=f.readLine()) != null && count++ < totalLines)
        System.out.println(line);
      f.close();
    }catch(IOException e) {
       e.printStackTrace();
    }
  }
}    

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?