I'm trying to accept 3 filenames through a command line. This is the code I tried but not working.. ?? Pls help
public class MedicalStudentMatcher {
enum Arguments {
HospitalFile, ResidentFile, OutputFile
};
/**
* #param args
*/
public static void main(String[] args) {
//Retrieve file locations from command line arguments
String hospitalFile = "";
String residentFile = "";
String outFile = "";
if (args.length > 2){
hospitalFile = args[Arguments.HospitalFile.ordinal()];
residentFile = args[Arguments.ResidentFile.ordinal()];
outFile = args[Arguments.OutputFile.ordinal()];
} else {
System.out
.println("Please include names for the preference files and output file when running the application.\n "
+ "Usage: \n\tjava MedicalStudentMatcher hospital.csv student.csv out.txt\n");
return;
}
Do some debugging. Print the length of you command line arguments as well as each argument
something like:
System.out.println(args.length);
for(String arg: args)
{
System.out.println(arg);
}
This way you will see what you are passing to your program as arguments.
Related
Description : Actually I am looking the java code which is basically running in the background, But whenever I want to open a new notepad or excel file , It will capture those file as an input and display the result in output console.
How I can do that , any one can help me on this.
The following mathod is based on Windows...
First of all, when opening files in software like Notepad and Excel, it is executed with a command line with parameters, that is, if Notepad is opened in E:\test.txt, the command line parameters for startup are
notepad E:\test.txt
In Windows, we can use the wmic command to get the startup parameters of an application. The specific usage is:
wmic process where caption="{exe_name}" get caption,commandline /value
For example, the cmd command to query the command line parameters opened in Notepad is:
wmic process where caption="notepad.exe" get caption,commandline /value
The returned result is similar to the following:
Caption=notepad.exe
CommandLine="C:\Windows\system32\NOTEPAD.EXE" H:\2019Summer\软件工程\任务.txt
The above "H:\2019Summer\软件工程\任务.txt" is the file I currently open by notepad.
What we need to do is to parse the result String, here is my example java code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class GetOpenedFile {
//QUERY_COMMAND
private static String QUERY_COMMAND = "wmic process where caption=\"{0}\" get caption,commandline /value";
private static String NOTEPAD_NAME = "notepad.exe";
private static String EXCEL_NAME = "excel.exe";
/**
* get execName command line
*
* #param execName like notepad.exe, excel.exe
* #return the all command line of the process {execName}
*/
private static List<String> getExecCommandLines(String execName) {
Runtime runtime = Runtime.getRuntime();
List<String> commandLines = new ArrayList<>();
try {
Process process = runtime.exec(MessageFormat.format(QUERY_COMMAND, execName));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GB2312"));//set your cmd charset(default value is utf8)
String caption = null;
while (true) {
String s = bufferedReader.readLine();
if (s == null) {
break;
}
if (s.length() == 0) {//skip blank string
continue;
}
//get the file name
if (s.startsWith("Caption")) {
caption = s.substring("Caption=".length());
continue;
}
if (s.startsWith("CommandLine=") && caption != null) {
int index = Math.max(s.indexOf(caption), s.indexOf(caption.toUpperCase()));//maybe the exe file name is ALL UPPER CASE, eg. NOTEPAD.EXE
index += caption.length()
+ 1;//Double quotes "
String commandLine = s.substring(index);// command Line
commandLine = commandLine.stripLeading();//strip leading white space
commandLines.add(commandLine);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return commandLines;
}
/**
* get notepad opened files
*
* #return notepad opened files
*/
public static List<String> getNotepadOpenedFiles() {
List<String> commandLines = getExecCommandLines(NOTEPAD_NAME);
return commandLines.stream()
.filter(s -> s.length() > 0)//skip empty command line
.collect(Collectors.toList());
}
/**
* get excel opened files
* #return excel opened files
*/
public static List<String> getExcelOpenedFiles() {
List<String> commandLines = getExecCommandLines(EXCEL_NAME);
return commandLines.stream()
.filter(s -> s.length() > 0)//skip empty command line
.map(s -> { //map result of "filename" to filename
if (s.startsWith("\"") && s.endsWith("\"")) {
return s.substring(1, s.length() - 1);
} else {
return s;
}
})
.collect(Collectors.toList());
}
public static void main(String[] args) {
//console printed
// [H:\2019Summer\软件工程\任务.txt]
// [E:\info.xlsx]
System.out.println(getNotepadOpenedFiles());
System.out.println(getExcelOpenedFiles());
}
}
I want to pass a variable to String filename variable below as a parameter. Can anyone help?? I checked the internet but could not find a good tutorial or example.
Thank you in advance...
import java.io.IOException;
public class JavaReadTextFile
{
public static String main(String[] args)
{
// This instantiates from another class
ReadFile rf = new ReadFile();
// The text file location of your choice.
// Here I want to pass a variable as a parameter to the variable filename
String filename = "";
try
{
String[] lines = rf.readLines(filename);
for (String line : lines)
{
//System.out.println(line);
return line;
}
}
catch(IOException e)
{
// Print out the exception that occurred
System.out.println("Unable to create " + filename + ": " + e.getMessage());
}
}
}
I'm assuming you mean "as an argument to my program", so that you can run:
java -jar myProgram.java theStringIWantToPass
If so, that's what main(String[] args) is for. All arguments will be put in there.. So, try using the following:
if (args.length > 0){
filename = args[0];
}
You didn't post a constructor, but you can get the (command line) parameter of your main function:
public static String main(String[] args) {
if (args!=null && args.length > 0) {
String filename = args[0];
}
}
Change your code to
String filename = args[0];
Now you can pass the file name as a program argument.
If you are open to use swing , then you can explore JOptionPane mesageBox , which can take input.
Otherwise the conventional way of reading the arguments while running the program from args array.
FileInputStream fstream = new FileInputStream("textfile.txt");
This is above code to get the input file , i want a input file to give from command line
i.e.
pseudo command line code
java filename giveinputfile("textfile.txt")
What change i modify in my java code and command line(windows) to make this work
You use the String[] args in your main method,
public static void main(String[] args) {
String fileName = "textfile.txt";
if (args.length > 0) {
fileName = args[0];
}
System.out.println("fileName: " + fileName);
}
Then you run your program with
java myProgram MY_FILE
or
java myProgram
With the code above the first command would use "MY_FILE" and the second would use the default "textfile.txt".
i am trying to pass a String value into a method which accepts Strings, however i am getting the error "incompatible types". i have tried hard coding a int value to see what error it gives which i expected it to:
found int; required: java.lang.String.
changed the method to accept File instead which errors:
found String; required: java.io.File.
ergo, i am feeding a string where a string should be. but i don't understand where i am going wrong. (and i have changed it back to feed String and accept String)
any feedback is welcome. thanks in advance :)
import java.io.*;
import java.util.*;
public class Test
{
private ArgsReader inputFile;
private String filename;
private List<Pallet> entryBayQueue;
/**
* Constructor for objects of class Test
*/
public Test()
{
inputFile = new ArgsReader();
entryBayQueue = new LinkedList();
}
/**
* methods
*/
public void run(String[] args)
{
if(args.length > 0) //launched if you gave an argument
{
String line;
filename = args[0];
System.out.println(filename.getClass().getSimpleName()); //outputs string
line = inputFile.stringFileReader(filename); //call method containing reading capability to read and store contents in line
// ******* here is where the error occurs
//System.out.println(line); //line = null here
StringTokenizer st = new StringTokenizer(line);//tokenize line's contents
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
int serialNum = 0;
switch(st.nextToken())
{
case "A":
{
serialNum++;
Pallet almondPallet = new Pallet(1,serialNum); //create new almond pellet and assign serial number
entryBayQueue.add(almondPallet); //adds pallet to the end of the list
break;
}
}
}
}
else //launched when you didn't provide an argument
{
filename = null;
Console console = System.console();
filename = console.readLine("file to read from: ");
inputFile.stringFileReader(filename); //call method containing reading capability
}
}
}
// ******this is the implementation of stringFileReader
public void stringFileReader(String filename)
{
try
{
input = new FileReader(filename); //open file for reading (string filename)
buffReader = new BufferedReader(input); // read a line at a time
line = buffReader.readLine(); //read 1st line
while (line != null)
{
lineNum++;
System.out.println(line);
line = buffReader.readLine(); //read next line
}
}
catch (IOException e){System.out.println("caught IOException");}
public void stringFileReader(String filename)
was supposed to be
public String stringFileReader(String filename)
method was not returning values when call is expecting.
thanks anyone who was helping.
I need my code to read in a file pathway and analyze the file at the end of it, and according to the assignment it has to exit if no valid pathway is given. when I type in something like "java ClassName pathway/file" though it just goes to accepting more input. If I then put in the exact same pathway it does what I want it to but it need to do it in the former format. should I not be using a Scanner?
(TextFileAnalyzer is another class I wrote that does the file analysis, obviously)
import java.util.Scanner;
public class Assignment8 {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String path = null;
TextFileAnalyzer analysis = null;
if (args.length == 0 || java.lang.Character.isWhitespace(args[0].charAt(0)))
System.exit(1);
try {
path = stdin.next();
analysis = new TextFileAnalyzer(path);
} catch (Exception e) {
System.err.println(path + ": No such file or directory");
System.exit(2);
}
System.out.println(analysis);
stdin.close();
System.exit(0);
}
}
Arguments specified on the command line are not the same as information entered via standard input at the console. Reading from System.in will let you read input, and this is not related to command line parameters.
The problem with your current, non-working code is that while you are checking to see if the argument was specified, you aren't actually using args[0] as the pathname, you're just going on to read user input regardless.
Command line parameters are passed in via the String[] parameter to main. In your case it's the first parameter, so it would be in args[0]:
public static void main (String[] args) {
String pathname;
if (args.length > 0) {
pathname = args[0]; // from the command line
} else {
// get pathname from somewhere else, e.g. read from System.in
}
}
Or, more strict:
public static void main (String[] args) {
String pathname;
if (args.length > 1) {
System.err.println("Error: Too many command line parameters.");
System.exit(1);
} else if (args.length > 0) {
pathname = args[0]; // from the command line
} else {
// get pathname from somewhere else, e.g. read from System.in
}
}
Check out the official tutorial on command-line arguments for more information.
By the way, I noticed you have this in your if condition:
java.lang.Character.isWhitespace(args[0].charAt(0))
Leading and trailing whitespace is automatically trimmed off of unquoted command line parameters, so that will always be false unless the user explicitly uses quotes and does something like:
java ClassName " something"
And even in that case, you may want to just accept it and use args[0].trim() to be more lenient.