I wrote a program that asks for user input like this:
System.out.println("Where would you like the output file to end up? (full path and desired file name): ");
Scanner out_loc = new Scanner(System.in);
output_loc = out_loc.nextLine();
...
System.out.println("Hey, please write the full path of input file number " + i + "! ");
System.out.println("For example: /home/Stephanie/filein.txt");
Scanner fIn = new Scanner(System.in);
I ask several times for input in this way but it can get to be a huge pain if you mistype because then you have to kill the program and rerun. Is there an easy way to just take input all at once when you run a program? As in just declaring it in the command line when having it run?
java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?
You can use file redirection.
program < file
sends the file to the standard input of the program. In your case,
java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere < file
Or you can read from a file in your program. You can make this optional like
InputStream in = args.length < 1 ? System.in : new FileInputStream(args[0]);
Scanner scan = new Scanner(in); // create the scanner just once!
When you run the command as :
java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?
It runs the public static void main(String[] args) method of your primary class where you can get the userinputhere directly as:
public static void main(String[] args)
String userinputhere = args[0];
..... rest of your code
}
If there are multiple user Inputs, you can get them all as :
public static void main(String[] args)
String userinput1 = args[0];
String userinput2 = args[1];
String userinput3 = args[2];
//and so on..
..... rest of your code
}
Related
This question already has answers here:
How do I pass parameters to a jar file at the time of execution?
(5 answers)
Closed 10 months ago.
I have my program saved in JAR format. I need to read data from two different files given by user using this line: java -jar app.jar file1.txt file2.txt. How can I read it? I wrote this:
Scanner scan = new Scanner(System.in);
String inputFileName1 = scan.next().trim();
String inputFileName2 = scan.next().trim();
File input1 = new File(inputFileName1);
Scanner file1 = new Scanner(input1);
File input2 = new File(inputFileName2);
Scanner file2 = new Scanner(input2);
It works when I manually write: file1.txt file2.txt, but not with the command line. What's wrong?
When you use command line to send the arguments, you can use args to access those arguments. For example, if you run java yourfile arg0 arg1 on the command line, then you can access arg0 and arg1 by using args[0] respectively args[1] in your code.
So, if you use
public static void main(String[] args) {
File input1 = new File(args[0]);
Scanner file1 = new Scanner(input1);
File input2 = new File(inputFileName2);
Scanner file2 = new Scanner(args[1]);
...
}
then your code should work fine.
You can get the arguments from the command line through the args from your main method.
Giving the args out would look something like this:
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
You could make something like File input1 = new File(args[0]); to get the first argument.
So I'm trying to accept a text file from the Linux command line into my Java program, but the compiler gives me that error mentioned in the title. It says the error occurs at the line that says "String fileName = args[0];". Does anyone happen to know why?
Here is my code:
public class Parsons_Decoder
{
// method: main
// purpose: receives key-phrase and sequence of integers and
// prints the secret message to the screen.
public static void main(String[] args) throws IOException
{
String fileName = args[0];
// reads incoming file (if it exists) and saves the key-phrase to
// String variable "keyPhrase"
File testFile = new File(fileName);
if(!testFile.exists())
{
System.out.println("\nThis file does not exist.\n");
System.exit(0);
}
Scanner inputFile = new Scanner(args[0]);
String keyPhrase = inputFile.nextLine();
// creates an ArrayList and stores the sequence of integers into it
ArrayList<Integer> numArray = new ArrayList<Integer>();
while(inputFile.hasNextInt())
{
numArray.add(inputFile.nextInt());
}
// decodes and prints the secret message to the screen
System.out.println();
System.out.print("Your secret message is: ");
for(int i = 0; i < numArray.size(); i++)
{
int num = numArray.get(i);
System.out.print(keyPhrase.charAt(num));
}
System.out.println("\n");
//keyboard.close();
inputFile.close();
}
}
Update:
Your professor is asking you to read in a file with stdin, using a command like the following:
java Diaz_Decoder < secretText1.txt
Your main() method should then look something like the following:
public static void main(String[] args) throws IOException {
// create a scanner using stdin
Scanner sc = new Scanner(System.in);
String keyPhrase = inputFile.nextLine();
// creates an ArrayList and stores the sequence of integers into it
ArrayList<Integer> numArray = new ArrayList<Integer>();
while (inputFile.hasNextInt()) {
numArray.add(inputFile.nextInt());
}
// decodes and prints the secret message to the screen
System.out.println();
System.out.print("Your secret message is: ");
for (int i = 0; i < numArray.size(); i++) {
int num = numArray.get(i);
System.out.print(keyPhrase.charAt(num));
}
System.out.println("\n");
}
Based on your description and the link you provided (which should be in the question, not a comment), your prof wants you to write a program that accepts the contents of a file via "standard in" (STDIN) when run as a POSIX style shell command line using redirection.
If this is indeed a requirement, you can't just read the file given as an argument, but need to change your program such that it reads from STDIN. The key concept here is that the "<" is not available to your program argument list. It will be consumed by the shell (Bash, Ksh, etc.) running the Java process, and a "pipe" setup between the file on the right side and the process on the left side. In this case, the process is your Java process running your program.
Try doing a search for "java STDIN" to get some ideas on how to write a Java program that can read its standard in.
By the way, if your program crashes with an ArrayIndexOutOfBoundError when run with redirection in this manner, it still has a bug in it. You need to test for and handle the case where you have 0 file arguments after the shell has finished processing the command line. If you want full marks, you need to handle the error and edge cases.
I'm trying to use 3 command line parameters such as:
java program textfile.txt test 3
The first one should access a textfile, the second one should print the name, and the third one should be a numeric key that is parsed as an integer.
import java.util.Scanner;
import java.io.*;
public class Program
{
public static void main(String[] args) throws IOException
{
String textfile=null;
String outtextfile=null;
String enteredKey=null;
for(String parameter: args) {
textfile = parameter;
outtextfile = parameter;
enteredKey = parameter;
}
Scanner s = new Scanner(new File(textfile));
//gets a string to encrypt
String str = s.nextLine();
//print outtextfile
System.out.println(outtextfile);
//gets a key
int key = Integer.parseInt(enteredKey);
However, that code yields this error:
-bash-4.1$ java Program sample.txt test 3
Exception in thread "main" java.io.FileNotFoundException: 3 (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:656)
at Program.main(Caesar.java:19)
You're running into a scoping problem:
The textFile variable is only visible within the for loop and is invisible outside of this loop. Are you sure that you even want to have a loop? And if so why? If the text file String is the first parameter, then get rid of the loop and only use the first parameter, args[0]:
public static void main(String[] args) throws IOException {
if (args.length == 0) {
// exit program with an error message
} else {
String textFile = args[0];
Scanner scanner = new Scanner(new File(textFile));
// do work with Scanner
}
You are declaring textfile in your loop, meaning it is only limited to the scope of your loop. You are trying to access it outside the loop. I would offer a suggestion, but I'm not really sure what you are trying to accomplish.
Try this :
String textfile=null;
for(String parameter: args) {
textfile = parameter;
}
Scanner s = new Scanner(new File(textfile));
I'm pretty new to Java still and I'm working on a project for class, and I'm unsure of how I write my program to take the userInput(fileName) and create a new object from that. My instructions are to write a program which reads in a file name from the user and then reads the data from that file, creates objects(type StudentInvoice) and stores them in an ArrayList.
This is where I am right now.
public class StudentInvoiceListApp {
public static void main (String[] args) {
Scanner userInput = new Scanner(System.in);
String fileName;
System.out.println("Enter file name: ");
fileName = userInput.nextLine();
ArrayList<StudentInvoice> invoiceList = new ArrayList<StudentInvoice>();
invoiceList.add(new StudentInvoice());
System.out.print(invoiceList + "\n");
}
You may try to write a class for serializing / deserializing objects from a stream (see this article).
Well, as Robert said, there's not enough information about the format of the data stored in the file. Suppose each line of the file contains all the information for a student. Your program will consist of reading a file by lines and create a StudentInvoice for each line. Something like this:
public static void main(String args[]) throws Exception {
Scanner userInput = new Scanner(System.in);
List<StudentInvoice> studentInvoices = new ArrayList<StudentInvoice>();
String line, filename;
do {
System.out.println("Enter data file: ");
filename = userInput.nextLine();
} while (filename == null);
BufferedReader br = new BufferedReader(new FileReader(filename));
while ( (line = br.readLine()) != null) {
studentInvoices.add(new StudentInvoice(line));
}
System.out.println("Total student invoices: " + studentInvoices.size());
}
can u help me with the coding of java, so i can copy a single file using command prompt.
so, i wanna run the java file from command prompt of windows, like "java "my java script" "my file target"" and make a copy of my "my file target" at the same directory without replace the old one.
please help me?
i came out with this
import java.io.*;
class ReadWrite {
public static void main(String args[]) throws IOException {
FileInputStream fis = new FileInputStream(args[0]);
FileOutputStream fos = new FileOutputStream("output.txt");
int n;
if(args.length != 1)
throw (new RuntimeException("Usage : java ReadWrite <filetoread> <filetowrite>"));
while((n=fis.read()) >= 0)
fos.write(n);
}
}
but the copy of the file is named as output.txt
can u guys help me with the coding, if i wanna choose my own output name?
if i type "java ReadWrite input.txt (this is the output name that i want)" on command prompt
really need help here...
import java.util.Scanner;
public class program_23{ // start of class
public static void main(String []args){ // start of main function.
Scanner input = new Scanner (System.in);
// decleration ang initialization of variables
String name = " ";
int age = 0;
int no_of_hour_work = 0;
double daily_rate = 0.0;
// get user input
System.out.print("Employee Name: ");
name = input.nextLine();
System.out.print("Employee Age: ");
age = input.nextInt();
System.out.print("No of hour(s) work: ");
no_of_hour_work = input.nextInt();
// compute for daily rate
daily_rate = no_of_hour_work * 95.75;
// display the daily rate
System.out.print("Dialy rate:"+ daily_rate);
}// end of main
}// end of class
pseudo-code:
input = open input stream for file1
output = open output stream for file 2
while (input.read() has more bytes):
write byte to output stream
close(input, output)