简体   繁体   English

如何修改此Java程序以从命令行中指定的文件中读取名称?

[英]How can I modify this Java program to read in the names from a file designated in the command line?

Right now I have this program set up to where I can input names of boats in the command line ie C:\\java Proj3 "Boat 1" "Boat 2" "Boat 3" and it prints the results to the command line based on the specs. 现在我将这个程序设置到我可以在命令行中输入船只名称的地方,即C:\\ java Proj3“Boat 1”“Boat 2”“Boat 3”,它将结果打印到基于命令行的命令行眼镜。 Instead, I want to type something like this in the command line C:\\java Proj3 "C:\\class\\Java\\boatnames.txt" "C:\\class\\Java\\results.txt" so the args come from the file specified and the results are printed in a text file instead of on the screen. 相反,我想在命令行C:\\ java Proj3“C:\\ class \\ Java \\ boatnames.txt”“C:\\ class \\ Java \\ results.txt”中输入类似的内容,因此args来自指定的文件并将结果打印在文本文件中而不是在屏幕上。 I changed the println's to printf's, but that's it so far. 我将println改为printf,但到目前为止就是这样。 I deleted all my other failed attempts at this. 我删除了所有其他失败的尝试。 I even tried creating another class called createfile.java that had private Formatter x; 我甚至尝试创建另一个名为createfile.java的类,该类具有私有的Formatter x; and some openFile, closeFile, and addRecords methods, but if I move the output over there and try to put it in addRecords, it doesn't know what the variable i is, and I'm guessing there must be a simpler way where I don't have to create that createfile class. 还有一些openFile,closeFile和addRecords方法,但如果我把输出移到那里并尝试把它放在addRecords中,它就不知道我是什么变量了,我猜我必须有一个更简单的方法不必创建该createfile类。

Here is my code(I didn't include the other classes since all I need to do is replace the args from the command line with args from a txt file in the command line): 这是我的代码(我没有包含其他类,因为我需要做的是用命令行中的txt文件中的args替换命令行中的args):

import java.util.*;
import java.io.*;
import java.lang.*;
import java.swing.*;

public class Proj3 {
    public static void main(String args[]) {

            Boat[] Boats;
        char   firstChar;
        char   secondChar;
        int    i;    

        Boats = new Boat[args.length];

        for (i = 0; i < args.length; i++) {

            firstChar = args[i].toUpperCase().charAt(0);
            secondChar = args[i].toUpperCase().charAt(1);

            if ((firstChar == 'B') || (firstChar == 'C') || (firstChar ==     'N')) {
                Boats[i] = new SailBoat();
            } else {
                Boats[i] = new RaceBoat();
            }

            Boats[i].setName(args[i]);

            if ((secondChar == 'A') || (secondChar == 'E')) {
            Boats[i].goFast();
            } else {
                Boats[i].goSlow();
            }
        }


        for (i = 0; i < args.length; i++) {
            System.out.printf("Boat number " + (i + 1) + " - \n");
            System.out.printf("   ");
            Boats[i].printBoat();
            System.out.printf("   ");
            Boats[i].whatIsBoatState();
        }




    }
}

The simplest way is to use an existing library to read the file in. A very-commonly used library is apache commons-io , which has the FileUtils.readLines() utility method. 最简单的方法是使用现有的库来读取文件。一个非常常用的库是apache commons-io ,它具有FileUtils.readLines()实用程序方法。

import org.apache.commons.io.FileUtils;

// pass the filename is to your program on the command line

List<Sting> lines = FileUtils.readLines(new File(args[0]));
for (String line : lines) {
    // use "line" instead of args[i] in your current code
    ...
}

Right now, the top-level program logic is contained in one monolithic main() method. 现在,顶级程序逻辑包含在一个单片main()方法中。 To make life easier, you should break it down into logical pieces and implement each piece in a separate method. 为了使生活更轻松,您应该将其分解为逻辑部分并以单独的方法实现每个部分。 For instance, your main() method might look something like this: 例如,您的main()方法可能如下所示:

public static void main(String[] args) {
    ArrayList<Boat> boats = getBoats(args[0]);
    PrintStream out = getOutputStream(args[1]);
    printBoats(boats, out);
    out.close();
}

Then you need to write the support routines: 然后你需要编写支持例程:

private ArrayList<Boat> getBoats(String inputFileName) {
    ...
}
PrintStream getOutputStream(String outputFileName) {
    ...
}
void printBoats(ArrayList<Boat> boats, PrintStream output) {
    ...
}

You will probably have to make it all a little more complicated to deal with I/O exceptions (missing files, write permissions, etc.). 您可能必须使处理I / O异常(丢失文件,写入权限等)变得更加复杂。 You'll also have to modify the methods Boat.printBoat() and Boat.whatIsBoatState() to take a PrintStream argument. 您还必须修改Boat.printBoat()Boat.whatIsBoatState()以获取PrintStream参数。

follow this 按照这个

java-Passing argument into main method java-将参数传递给main方法

obtain the files base don absolute path and obtain the file object then read the file object to pickup the content. 获取文件base don绝对路径并获取文件对象然后读取文件对象以拾取内容。

I've not tested this, but I've not tested it any great detail 我没有对此进行过测试,但我没有对其进行任何细节测试

public static void main(String[] args) {

    if (args.length == 2) {

        String inFileName = args[0];
        String outFileName = args[1];

        File inFile = new File(inFileName);
        if (inFile.exists()) {

            try {

                List<Boat> boats = new ArrayList<Boat>(25);

                // Read the "boats" file...
                BufferedReader br = null;
                try {

                    br = new BufferedReader(new FileReader(inFile));
                    String text = null;
                    while ((text = br.readLine()) != null) {

                        char firstChar = text.toUpperCase().charAt(0);
                        char secondChar = text.toUpperCase().charAt(1);

                        Boat boat = null;
                        if ((firstChar == 'B') || (firstChar == 'C') || (firstChar == 'N')) {
                            boat = new SailBoat();
                        } else {
                            boat = new RaceBoat();
                        }

                        boat.setName(text);

                        if ((secondChar == 'A') || (secondChar == 'E')) {
                            boat.goFast();
                        } else {
                            boat.goSlow();
                        }

                        boats.add(boat);

                    }

                } finally {
                    try {
                        br.close();
                    } catch (Exception e) {
                    }
                }

                BufferedWriter bw = null;
                try {

                    bw = new BufferedWriter(new FileWriter(outFileName, false));
                    for (int index = 0; index < boats.size(); index++) {

                        bw.write("Boat number " + (index + 1) + " - ");
                        bw.newLine();
                        bw.write("    " + boat.toString() + "    " + boat.getBoatState());

                    }

                    bw.flush();

                } finally {
                    try {
                        bw.close();
                    } catch (Exception e) {
                    }
                }

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

        }

    }

}

The other problem is, you're going to need to provide some additional functionality to your Boat class 另一个问题是,您需要为Boat类提供一些额外的功能

Namely, I used boat.toString() which needs to return the value Boat.printBoat() was printing and boat.getBoatState() which needs to return the value that Boat.getBoatState() was printing 也就是说,我使用了boat.toString() ,它需要返回值Boat.printBoat()打印和boat.getBoatState() ,它需要返回Boat.getBoatState()打印的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 修改 java 代码从 Linux 命令行读取输入文件 - Modify java code to read input file from Linux command line 如何从命令行在Java中读取文件? - How to read file from command line in java? 如何使用扫描仪从命令行读取文件 - How can I read a file from the command line using scanner 如何从Java在命令行中运行ruby文件? - How can I run a ruby file in command line from Java? 我可以使用命令行/脚本来修改已经运行的Java程序中的变量吗 - Can I use the command line/a script to modify variables in a java program that is already running 如何修改此Java命令行程序以搜索字符串并打印出该字符串出现的次数? - How do I modify this java command line program to search for a string and print out the number occurrences of that string? 如何从Python程序创建的文件中读取Java程序中的RDD - How can I read RDD in my java program from a file that was created by Python program 如何让 java 程序从文件中只读取一行? - How do I make a java program read just one line from the file? 如何从Java程序在Linux中打开另一个命令行应用程序? - How can I open another command line application in Linux from a Java program? 如何从 java 程序中的命令行参数获取 ssh 关键数据? - How can I get an ssh key data from a command line argument in java program?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM