简体   繁体   中英

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. 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. I changed the println's to printf's, but that's it so far. I deleted all my other failed attempts at this. I even tried creating another class called createfile.java that had private 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.

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):

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.

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. 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:

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.). You'll also have to modify the methods Boat.printBoat() and Boat.whatIsBoatState() to take a PrintStream argument.

follow this

java-Passing argument into main method

obtain the files base don absolute path and obtain the file object then read the file object to pickup the content.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM