2

我是 JAVA 的新手。我已经完成了一些教程,我正在下一步检查我现在的表现。请随时批评下面的代码块。任何反馈表示赞赏。谢谢!

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.Vector;

import org.apache.log4j.helpers.FileWatchdog;


/**
* 
* Simple class that reads in a file - sorts its lines in natural order,  
* writes it back out to the given filename and adds a timestamp of when it was sorted
* 
* Program will be called with:
* 
* java TestClass <input_filename> <output_filename>
*
*/

public class TestClass {


public static void main(String [] args) throws RuntimeException{
    boolean OVERWRITE_FILE = true;
    //get filename from args
    String inputFilename = args[0];
    String outputFilename = args[1];

    //check usage
    if(args.length != 2){
        System.out.println("Incorrect number of args");
        System.out.println("Correct usage is:");
        System.out.println(" java TestClass <input_filename> <output_filename> ");
        System.exit(-1);
    }

    //read in file into collection
    try {
        BufferedReader in = new BufferedReader(new FileReader(inputFilename));
        Vector fileContents = new Vector<Object>();
        while(in.ready()){
            fileContents.add(in.readLine());
        }

        //sort the collection in natural order
        Collections.sort(fileContents);

        //add timestamp
        fileContents.add("File Sorted on: ");
        fileContents.add(new Date());

        //write outputFile
        BufferedWriter out = new BufferedWriter(new FileWriter(outputFilename, OVERWRITE_FILE));
        for(int i = 0; i < fileContents.size(); i++){
            out.write((String)fileContents.get(i) + "\n");
        }
        //close output file
        out.close();

    } catch (IOException e) {
        System.out.println("Error while performing IO");
    }

}
}

有没有更好的方法来做到这一点?

4

0 回答 0