有没有办法让这个Java程序更具交互性?

时间:2012-08-31 12:30:54

标签: java

我编写了以下非常简单的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语句中捕获该异常并打印出堆栈跟踪。但是,我认为它不是非常用户友好,有没有办法,如果文件不存在,那么整个过程从头开始重启?
  3. 提前致谢。

3 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分: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...
}

答案 2 :(得分: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());
        }

    }
}