Reading data from file given by user [duplicate] - java

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.

Related

Input file for JAR

I want to send the input of a jar from one file and save the output in another,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> builder = new ArrayList<>();
String line;
while (!(line = sc.nextLine()).isBlank()) {
builder.add(line);
}
builder.stream().sorted().forEach(System.out::println);
sc.close();
}
when I execute the jar I try it like this
java -jar name.jar > output.txt < input.txt
but it generates the exception java.util.NoSuchElementException, I appreciate any help.
This is what I believe is the easiest way to accomplish what you are trying to do:
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("output.txt"); // Used to write to output.txt
Scanner sc = new Scanner(System.in);
List<String> builder = new ArrayList<>();
while (sc.hasNextLine()) { // Same thing as what you had, just 1 less line
// Not entirely sure what you're trying to do here;
//if no input is given at the EXACT time the program is run, this will be skipped
builder.add(sc.next());
}
builder.stream().sorted().forEach((s) -> { // Changed this to a lambda
System.out.println(s);
try {
fw.write(s);
} catch (IOException e) {
e.printStackTrace();
}
});
fw.close();
sc.close();
}
The easiest way would be to pass your input.txt file as a parameter to your jar. You can then utilize Files.readAllLines to read your text file and do your sort and then send each line to std out
Then you can redirect std out to your output.txt file.
public static void main(String[] args) throws IOException {
if (args == null || args.length == 0) throw new RuntimeException("No file provided");
Path file = Paths.get(args[0]);
if (Files.notExists(file)) throw new IOException(args[0] + " cannot be found.");
Files.readAllLines(file).stream().sorted().forEach(System.out::println);
}
Then you can invoke it like this:
java -jar name.jar input.txt > output.txt
The code is okay, not perfect, but it works. Of course your class needs to have some more lines (like defining the import and class definition etc.), but you only posted the main method is and that's okay for me.
At runtime, you're piping < input.txt as your standard input which is great.
I think your problem could be:
Your input.txt contains nothing, then you'll get this exception
Or the input.txt is in a different directory at runtime, so you're actually not piping anything as an input. There's no error from the command line, but this way you get the exception too.
One of those could be the cause.

ArrayIndexOutOfBoundsException:0 occurs when trying to read in a file from the Linux command line in Java?

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.

passing input file in java through command line

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".

User input other than print prompt and scanner

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
}

how to make a copy-paste script with jcreator?

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)

Categories

Resources