简体   繁体   中英

Sending arguments from the command line in java

I'm relatively new to java and would like to generate a program that reads text from pdf based on a command line argument I provide. In this example, I'd like to pass the file document.pdf (in the same directory as my jar file). I have also tried sending files from my desktop using /home/myname/Desktop/document.pdf (to see if this is a relative / absolute path issue). I continue to get a file not found error. I thought with the following invocation I am sending the files path as args[0] to the program ..

java -jar fileRead.jar fileRead document.pdf

---or--- 

java -jar filereadjar fileRead /home/myname/Desktop/document.pdf

if i replace filesInputStream(args[0]); with filesInputStream("/home/myname/Desktop/document.pdf"); in the program, all goes well. So why isn't the path getting sent to the filesInputStream from the command line?

Thanks.

package fileRead;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;


import org.apache.tika.parser.pdf.PDFParser;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;

public class fileRead {

      public static void main(String args[]) throws Exception {

            InputStream is = null;
            try {
              is = new FileInputStream(args[0]);
              ContentHandler contenthandler = new BodyContentHandler(-1);
              Metadata metadata = new Metadata();
              PDFParser pdfparser = new PDFParser();
              pdfparser.parse(is, contenthandler, metadata, new ParseContext());

              PrintWriter writer = new PrintWriter("/home/marek/Downloads/the-file-name.txt", "UTF-8");
              writer.println(contenthandler.toString());
              writer.close();
            }
            catch (Exception e) {
              e.printStackTrace();
            }
            finally {
                if (is != null) is.close();
            }
          }

}

To answer formally then:

java -jar <jarname> <args...> will invoke the main class of an executable JAR.

java -cp <jarname> <classname> <args...> will invoke the specified class of a JAR (not necessarily executable).

If you put the classname in the first syntax, it actually becomes the first parameter, so your args array is shifted by one position since a useless fileRead parameter enters the fray.

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