简体   繁体   中英

How to get File name from cmd argument to create a copy?

I'm working on a program that reads from a file with a custom extension I made. The idea is that an error report is created every time a file is read. The error report must be in whatever folder the source file was called from. The error file is a copy of the source file, but it has a line number at the beginning of each line and indicates at the end of the line if an error occurred at that line. (I'm not trying to set up the numbering on this question, this question is just about creating the copy)

So for example, when I call my program from the command prompt:

C:\MyLocation>java =jar myJavaProgram.jar myFileToRead.CustomExtension 

Asides from reading the file, it should also create a copy at the same location called myFileToRead-ErrorReport.txt Additionally: If the source file has no extension, I have to assume that it's still the correct extension, so there won't always be a '.myCustomExtension' segment to replace into .txt

The problem is that I don't know how to grab the file name, because it's coming from the args list of the main method. I am using the following to read the file

public static void main(String[] args) throws FileNotFoundException {
        try{
            File inputFile = new File(args[0]);
        
            Scanner sc = new Scanner(inputFile);
            while(sc.hasNext()){
                System.out.println(sc.nextLine());
            }
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage());
            System.out.println("File not found.");
        }
    }

So how can I get that file name to make something like

File errorReport = new File("./" + inputFileName + ".txt"); ?

First the code. The explanations appear after the code.

public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("ERROR: Missing filename argument.");
    }
    else {
        String filename = args[0];
        if (filename.length() == 0) {
            System.out.println("ERROR: Empty filename argument.");
        }
        else {
            if (!filename.endsWith(".CustomExtension")) {
                filename += ".CustomExtension";
            }
            String name = filename.substring(0, filename.indexOf(".CustomExtension"));
            name += "-ErrorReport.txt";
            File inputFile = new File(filename);
            File directory = inputFile.getParentFile();
            File errorReport = new File(directory, name);
            System.out.println(errorReport.getAbsolutePath());
        }
    }
}

I make it a habit of checking the parameters. Hence I first check that the file name was supplied. If it was, then I check that it is not an empty string. Note that I have omitted some checks, for example checking whether the named file exists and is readable.

You wrote in your question that the file name argument may or may not include the .CustomExtension . Hence I check whether the supplied name ends with the required extension and append it if necessary. Now, since I know what the file name ends with, that means that the required part of the name is everything up to the extension and that's what the call to substring() gives me.

Once I have the required name, I just append the part that you want to append, ie -ErrorReport.txt .

Method getParentFile() in class java.io.File returns the directory that the file is located in. Hence I have the directory that the input file is in. Finally I can create the error report file in the same directory as the input file and with the desired file name. For that I use the constructor of class java.io.File that takes two parameters. Read the javadoc for details.

Note that creating a File object does not create the file. Creating an object to write to the file does, for example FileWriter or OutputStreamWriter .

Here is the code example to create a file, with filename passed from cmd line as argument and to get the same file name :

Class Demo{
         public static void main(String[]args){
        String path ="<path of file>"
        String name= args[0];
        File f = new File(path+name+".txt");
        f.createNewFile(); //create file
    System.out.println(f.getName()); // will give you the file name
    }
 }

cmd line : java -cp . Demo.java <filename>

Note : ' . ' used in the cmd if your class file is present in current dir

You can refer the code and modify to suit your requirement. Hope this is what you are looking for.

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