1

我编写了以下非常简单的 Java 程序,要求用户输入文件名,然后它将该文件的行数报告到标准输出:

import java.io.*;
import java.util.*;

public class CountLine {

 public static void main(String[] args) 
 {

     //  prompt the user to enter their file name
    System.out.print("Please enter your file name: ");

    //  open up standard input
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String fileName = null;

      //  read the username from the command-line; need to use try/catch with the
      //  readLine() method
      try {
         fileName = br.readLine();
      } catch (IOException ioe) {
         System.out.println("IO error trying to read your name!");
         System.exit(1);
      }

      System.out.println("Thanks for the file name, " + fileName);



    File file = new File("C:/Users/Will/Desktop/"+fileName);
    Scanner scanner;
    try {
        scanner = new Scanner(file);

    int count =0;
    String currentLine;

    while(scanner.hasNextLine())
    {
        currentLine=scanner.nextLine();
        count++;

    }

    System.out.println("The number of lines in this file is "+count);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        System.out.println("There is no such file");
        e.printStackTrace();
    }
}

}

它正在工作。如果专家能帮助我,我将非常感激

  1. 看看这个代码片段有什么可以改进的,
  2. 如果未找到该文件,则在最外层的 catch 语句中捕获异常并打印出堆栈跟踪。但是,我觉得不是很人性化,有没有办法如果文件不存在,那么整个过程从头开始?

提前致谢。

4

3 回答 3

1

明显的变化是创建一个countLines(String filename)包含当前 main() 中的大部分代码的方法。显然 main() 将调用 countLines()。

提示文件可能存在于 main() 或其他方法中。

要重新启动错误,您需要一个循环,例如:

filename = // read filename from stdin;
while(keepGoing(filename)) { // null check or whatever to let you out of the loop
    try {
         int numLines = countLines(filename);
         println("num lines in " + filename + "=" +numLines);
    }
    catch(Exception ex) { // or just specific excpetions
        ex.printStackTrace();
    }
}
于 2012-08-31T12:37:13.240 回答
1

在您的代码中获取一些结构:

public static void main(String[] args) 
{
  string output;
  string fname = readFileName();
  if (fileValid(fname)) //Ensure FileExists
  {
     int lineCount = scaneFile(fname);   
     output = "some output text including line numbers"   
  }  
  else
  {
    output = "File Not Valid..."
  }
  //showOutput...
}
于 2012-08-31T12:43:08.713 回答
0

除非你想制作一个 GUI。我建议您将文件的路径作为命令行参数接收。

如果文件不存在,则打印一条消息并退出。就这样。

命令行将为用户提供使用向上键向上移动、编辑名称并再次运行的选项。

这个类被命名为 LineCounter,是“业务逻辑”

package countlines;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class LineCounter {

    private int lineCount = 0;
    public LineCounter(File file) throws IOException{
        BufferedReader inFile = new BufferedReader(new FileReader(file));
        while(inFile.readLine() != null) {
            lineCount++;
        }
        inFile.close();
    }

    public int getLineCount() {
        return lineCount;
    }   

}

这个类是“表示逻辑”

package countlines;

import java.io.File;
import java.io.IOException;

public class Main {
    public static void main (String[] args){
        if (args.length != 1){
            System.out.println("Usage: java countlines/Main filePath");
            System.exit(1);
        } 

        File f = new File(args[0]);

        if (!f.exists()){
            System.out.println("File "+f.getAbsolutePath()+" doesn't exist");
            System.exit(2);
        }

        if (f.isDirectory()){
            System.out.println(f.getAbsolutePath()+" is a directory");
            System.exit(2);         
        }

        LineCounter c;
        try {
            c = new LineCounter(f);
            System.out.println(c.getLineCount());
        } catch (IOException e) {
            System.out.println("Error reading file " + f.getAbsolutePath());
        }

    }
}
于 2012-08-31T13:13:13.650 回答