0

コマンドラインでこのプログラムに「lab13.txt」を読み込ませるにはどうすればよいですか? 私はこれを1時間以上理解しようとしてきましたが、何もうまくいかないようでした。

プロンプトは、「コマンド ラインで指定した名前のファイルの行数を決定して表示するプログラムを作成します。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 に答える