This question already has answers here:
How to get around the command line length limit?
(9 answers)
Closed 9 years ago.
I am writing a code that accepts a list of files as an input. I am doing stress testing and an error occurs if there are a lot of files as an input.
My main function accepts an array of Strings as an input.
public static void main(String[] args)
I have around 200 files as an input. My args accepts input in this format:
-f <file path>
At one point on the list of files, Java will throw a File Not Found exception because it gets an incorrect path. There is always only one character missing. And the preceding file entries are read correctly.
I tried to get the length of the string when one character got missing, and it is always on 8090th character.
Example:
If I have a list of files in a nested directory. My input will be something like this.
-f test\test1\test1_test2\test1_test2_test3\test3_test4.txt
Repeated inputs of this kind would result to:
-f test\test1\test1_test2\test1_test2_test3\test3_test4.txt
...
-f test\test1\test1_**tst2**\test1_test2_test3\test3_test4.txt
...
-f test\test1\test1_test2\test1_test2_test3\test3_test4.txt
There is a missing "e" which should be the 8090th character. But the next file entries are being read correctly. What am I missing?
Quoting MS Support
In Command Prompt, the total length of the following command line that you use at the command prompt cannot contain more than either 2047 or 8191 characters (as appropriate to your operating system)
So this means you cannot pass arguments to your program longer than 8191 characters. But workaround could be storing your arguments into the file and pass that file through command line to your program.
Make a second main class, where the main reads a file with the arguments.
public class MainWithArgsFile {
public static void main(String[] fileArgs) {
List<String> args = new ArrayList<>();
// Fill args:
for (String fileArg: fileArgs) { // One or more files.
try (BufferedReader in = new BufferedRead(new InputStreamReader(
new FileInputStream(new File(fileArg)), "UTF-8"))) {
for (;;) {
String line = in.readLine();
if (line == null) {
break;
}
//args.add(line); // One arg per line (for instance).
Collections.addAll(args, line.split(" +"));
}
}
}
OriginalMain.main(args.toArray(new String[args.size()]);
}
}
Related
I am getting error while taking input with Integer.parseInt(args[0]); error is in args section i know i can change it to scanner but i want to know this method.
Can anybody point out or show the solution to my problem?
class NegativeOutputException extends Exception{
private final int ex;
NegativeOutputException(int a){
ex = a;
}
public String toString(){
return "NegativeOutputException!("+ex+")";
}
}
public class practice6_creating_custom_exception {
public static void main(String args[]){
int x = Integer.parseInt(args[0]);//Error Here argument at position one
int y = Integer.parseInt(args[1]);//argument at position two
//argument at position twenty one which doesn't exsist
int a;
try{
a = x * y;
if(a < 0)
throw new NegativeOutputException(a);
System.out.println("Output >>" + a);
}
catch(NegativeOutputException e){
System.out.println("Caught >>" + e);
}
}
}
Output::
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at practice6_creating_custom_exception.main(practice6_creating_custom_exception.java:21)
Process finished with exit code 1
It gives you a java. lang.ArrayIndexOutOfBoundsException because you are trying to access a position in an empty array.
parseInt() is not used for taking inputs in such a case you need to use Scanner
For your case, you need first take input (by using Scanner) and then assign it to an integer variable, directly parsing the argument array will not provide the input.
Scanner sc = new Scanner();
int x = sc.nextInt(); //Scans the next token of the input as an int
parseInt() function -
The parseInt() method parses a value as a string and returns the first integer.
Source
Scanner Class -
Scanner object holds the address of InputStream object present in the
System class. Input Stream object of system class reads data from the
keyboard which is byte stream/byte form. The Scanner class converts
this read byte into a specific data type.
Source
The parseInt() function cannot read data from the input stream which is byte stream/byte form, hence you cannot directly parse the args[] array and assign it to an integer variable as it is empty since it is not yet scanned.
If you are looking for different ways of taking input in Java then here they are:
Using Buffer Reader Class,
Using Scanner Class,
Using Console Class,
Using Command Line Argument,
Source
Most probably you are simply not passing any arguments.
One way to pass arguments to the main method in Java is with the command to run the application in terminal. You can simply add the arguments after the java command to run the application separating them with a space. If you want the user to input the data, then you should use Scanner instead.
In your case, navigate to the folder where your java file sits and run the following:
java practice6_creating_custom_exception 0 1
In this example, 0 and 1 are the arguments you are passing.
If you are using an IDE then this can usually be done in the run configurations.
Side note, you might need to compile the application before running it and the command for that is the following:
javac practice6_creating_custom_exception.java
So, I am writing a program where I am reading from a file one character at a time, doing an operation with the character, then writing the output to a different file.
For some reason I get a different result when I hard code the file path (I did that just so I didn't have to keep typing the file while debugging) and when I pass the files from the command line.
When I pass the file from the command line it will skip input lines sometimes, so if I had a file with 10 lines I may only get 8 lines being processed.
I have a feeling it has something to do with whether or not there are spaces at the end of the input lines but I can't seem to figure it out. Any help would be much appreciated.
Also, I was using NetBeans when I hardcoded the file path, and ran the program from the terminal when I used command-line arguments. I have pasted the I/O code below.
while( ( i = buffRead.read() ) != -1 )
{
try
{
char c = (char) i;
if ( Character.isWhitespace(c) )
{
if(converter.getStackSize() > 1)
{
converter.resetConverter();
throw new IncorrectNumOfOperandsException();
}
buffRead.readLine();
converter.resetConverter();
writeOut.println();
}
else
{
converter.register( c );
}
}
catch (InvalidCharException j)
{
writeOut.println("Invalid Character Entered\n");
buffRead.readLine();
}
catch (IncorrectNumOfOperatorsException k)
{
writeOut.println("Too Many Operators for Number of Operands\n");
buffRead.readLine();
}
catch ( IncorrectNumOfOperandsException m)
{
writeOut.println("Too Many Operands for Number of Operators\n");
buffRead.readLine();
}
}
buffRead.close();
writeOut.close();
I think I see the problem.
You test c to see if it is a whitespace character, and if it is, you then call readLine(). What readLine() does is to read one or more characters until it gets to the next end-of-line sequence.
So what happens when c contains a newline character?
newline is a whitespace character (look it up)
so you read a line, starting at the first character after the newline that you just read
and discard the line.
So you have (accidentally) thrown away a complete line of input.
The solution ... I will leave to you.
When I pass the file from the command line it will skip input lines sometimes ...
I suspect that the same behavior was happening when you were typing the input ... but you didn't notice it. But it is possible that there is something going on with platform specific line termination sequences.
Unfortunately the code you provided seems to have nothing to do with the question!
Where are the 2 different ways of obtaining File?
Also, try using the try-with-resources statement. Something like this:
try(final Reader rdr = new InputStreamReader(System.in);
final BufferedReader brd = new BufferedReader (rdr))
{
/*
* Resources declared above will be automatically closed.
*/
brd.readLine();
}
...it will ensure all files are closed.
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
The method should read the contents of a file line by line and add each line to the array list. It should end once it reaches a solitary "." (period) or no more lines.
The problem is that I can not figure a way to check the contents of the next line without skipping lines since I am using nextLine numerous times. I am limited to the use of hasNext and nextLine.
public static ArrayList<String> getList(Scanner in) {
ArrayList<String> list = new ArrayList<String>();
while(in.hasNext() && !in.nextLine().equals("."))
{list.add(in.nextLine());}
return list;}
As written the output will skip lines to output lines 2, 4, 6 etc
when I need it to output 1,2,3,4 etc.
I am sure I am simply not seeing the way to solve the issue but any hints specifically on how to get it working by reformatting what I have with the methods listed are appreciated.
Just store the line in a variable:
public static List<String> getList(Scanner in) {
List<String> list = new ArrayList<String>();
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals(".")) {
break;
}
else {
list.add(line);
}
}
return list;
}
I am wondering how to pass a file as an argument on linux command line.
public class Main {
public static void main(String[] args){
System.out.println(args[0]);
}
}
For the above code if I do:
java -jar myJava.jar blah.txt
It prints blah.txt to the screen.
But I have a sample line of code that looks like this:
java -jar myJava.jar < blah.txt
How am I able to get the value of blah.txt from the above command?
Use one of the techniques for reading from System.in where the file is being redirected such as Scanner
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
...
}
try the following
java -jar myJava.jar 'blah.txt'
The quotes indicate that the argument is literal.
double quotes will also work, but will not prevent things like variable expansion, so single quotes is better when trying to pass a literal string.
I am new to java and I am trying to do an assignment where I have to read in data from a text file where the text file has the total number of items in the lists in the first line and the height, weight and the name data in the following. Since there are 5 data points, the first integer in the file is '5' and the following 5 lines are the respective datas that I am scanning.
it seems like I have trouble running this code from the command line but I can run it from netbeans. I am getting the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundExceptions:0 at bmi.Bmi.main<Bmi.java:18>
Code
public static void main(String[] args) {
System.out.println("\nBMI Report:");
File file = new File (args [0]);
try{
Scanner scanner = new Scanner(new FileInputStream(file));
int count=scanner.nextInt();
for(int i=0;i<5;i++){
int height=scanner.nextInt();
int weight=scanner.nextInt();
String name=scanner.nextLine();
Exception in thread "main" java.lang.ArrayIndexOutOfBoundExceptions:0 at bmi.Bmi.main
This message means that element 0 was accessed, going beyond the bounds of the array, in other words the array is empty so this doesn't work.
This must be the problematic line in your pasted code:
File file = new File (args [0]);
If args is empty, that will raise the exception as in your post. Your program requires an argument. Of you pass it an argument, that should resolve your problem.
You might want to add a check first and print a helpful message, for example:
if (args.length < 1) {
System.out.println("You need to specify an argument. Bye.");
System.exit(1);
}
File file = new File (args [0]);
// ...