0

我怎样才能让这个程序在命令行中读取“lab13.txt”?我一直试图解决这个问题一个多小时,但似乎没有任何效果。

提示是“编写一个程序,确定并显示您在命令行中指定名称的文件中的行数。使用 lab13.txt 测试您的程序。”

import java.util.Scanner;
import java.io.*;
class homework
{
    public static void main(String[] args) throws IOException
    {
        Scanner inFile= new Scanner(new File("lab13.txt"));
        int count=0;
        String s;
        while (inFile.hasNextLine())
        {
            s = inFile.nextLine();
            count++;
        }
        System.out.println(count + " Lines in lab13.txt");
        inFile.close();
    }
}
4

3 回答 3

0

如果您希望用户能够在 Eclipse 中从命令行或控制台输入文件名,请尝试使用此

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter filename : ");
    String filename = null;
    try {
        filename = reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    } 

然后,您可以将文件名插入您的 Scanner 对象

于 2013-11-22T17:54:52.137 回答
0

http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html

在程序名称之后添加到命令行的内容进入 args 数组,因此:

Scanner inFile= new Scanner(new File(args[0]));
于 2013-11-22T17:54:52.793 回答
0
Try this

在您的代码中,您需要替换new File("lab13.txt")new File(args[0])

对于命令行

public static void main(String[] args) {

File inFile =null;
  if (0 < args.length) {
      File inFile = new File(args[0]);
  }

    BufferedReader br = null;

    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader(inFile));

        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
        }

    } 

    catch (IOException e) {
        e.printStackTrace();
    } 

    finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

对于特定位置

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

public class BufferedReaderExample {

    public static void main(String[] args) {

        BufferedReader br = null;

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader("C:\\lab13.txt"));

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}
于 2013-11-22T17:54:56.257 回答