How do you process information in Java that was input from a file. For Example: suppose you have a file input.txt. The contents of this file is:
abcdefghizzzzjklmnop
azzbcdefghijklmnop
My hope would be that the information would be put into the argument array of strings such that the following code would output "abcdefghizzzzjklmnop"
class Test {
public static void main(String[] args) {
System.out.println(args[0]);
}
}
The command I have been using throws an array out of bound exception. This command is:
java Test < input.txt
Non-file based arguments work fine though. ie. java Test hello,a nd java Test < input.txt hello.
More information:
I have tried putting the file contents all on one line to see if \n \r characters may be messing things up. That didn't seem to help.
Also, I can't use the bufferedreader class for this because this is for a program for school, and it has to work with my professors shell script. He went over this during class, but I didn't write it down (or I can't find it).
Any help?
You should be able to read the input data from System.in.
Here's some quick-and-dirty example code. javac Test.java; java Test < Test.java:
class Test
{
public static void main (String[] args)
{
byte[] bytes = new byte[1024];
try
{
while (System.in.available() > 0)
{
int read = System.in.read (bytes, 0, 1024);
System.out.write (bytes, 0, read);
}
} catch (Exception e)
{
e.printStackTrace ();
}
}
}
It seems any time you post a formal question about your problem, you figure it out.
Inputing a file via "< input.txt" inputs it as user input rather than as a command line argument. I realized this shortly after I explained why the bufferedreader class wouldn't work.
Turns out you have to use the buffered reader class.
I'm not sure why you want to pass the contents of a file as command line arguments unless you're doing some weird testbed.
You could write a script that would read your file, generate a temporary script in which the java command is followed by your needs.
Related
This question already has answers here:
Reading a plain text file in Java
(31 answers)
Closed 7 years ago.
So for an project, we need to have the program accept the file name to be read in from command line arguments of main method. That is, your program should be executable from the command line by calling:
~>java Project inputFile.txt
Which will output the modified contents of the file to the standard output.
But I am clueless on how to do this.
PS: We've covered how to use the command line arguments but not how to have a file read from this location. Any suggestions?
Say, you invoke your program as
java MyMainClass /path/to/file
Then in the main() method just use
File f = new File(args[0])
Then, you might want to validate that
f.exists()
f.isFile()
f.canRead()
etc.
To actually read the file you can follow those instructions as suggested in the comment by #Kevin Esche
java MainClass <list of arguments>
Now in main class you will receive all the argument in String array, which is passed in the main method.
public static void main(String args[]) {
for(String argument : args) {
System.out.println(argument);
}
}
When running a java program from the console you call:
java programName list of inputs separated by space
So in your case you have:
java Project inputFile.txt
When the JVM starts and calls main() it will take everything after your project name and create a String array of that separated by the spaces.
So in my first caommand line I would get:
{"list" + "of" + "inputs" + "separated" + "by" + "space"}
This string array will come into your program in the main function:
public static void main(String[] args) { ... }
Therefore, in your case, args[0] will be the file name you are looking for. You can then create a file reader of sorts. If you don't add any path to the front of the file name it will look for the file in the folder that your src folder is in.
Hope this helps.
Maybe this would help, it reads and prints the file to the console.
public static void main(String[] args) {
File f= new File(arg[0]);
InputStream is = new FileInputStream(f);
int byteReaded;
while ((byteReaded = is.read())!=-1) {
System.out.print((char)byteReaded);
}
}
I am trying to compile and run this program by using eclipse. How do I do this?
I cant include the command line in the program. how do i use eclipse to run the program by using this command line??
I know theres another way of making the program by using Scanner but how do i run this one properly???
Cant post an image. Just joined.
INPUTTING FROM A FILE
Display a text file.
/*To use this program, specify the name
of the file that you want to see.
For example, to see a file called TEST.TXT,
use the following command line.
java ShowFile TEST.TXT */
import java.io.*;
class ShowFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException exc) {
System.out.println("File Not Found");
return;
} catch(ArrayIndexOutOfBoundsException exc) {
System.out.println("Usage: ShowFile File");
return;
}
// read bytes until EOF is encountered
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
Right click on your program, Hover over to Run As and Click Run Configurations
You will see a dialog box, now click on Arguments tab and specify the command line arguments.
I am not sure what you are asking, but to view the output of your program in the console:
You can do:
Window > Show View > Console
If you want to you want to compile from the command line you can use javac.
Right click on your program, Hover over to Run As and Click Run Configurations You will see a dialog box, now click on Arguments tab and specify the command line arguments.
On Program Arguments simply write file name OR file Address No need to write java ShowFile in your case it will be TEST.TXT .
Note : Make sure that TEST.TXT file is in your project folder
So, I'm trying to read a file like by line in java and compare it to all the words in another file and see how many of them match.
public static void main(String[] args) {
int i = 0;
int wordFound = 0;
String wordCheck;
File file = new File("wordlist.txt");
File input = new File(args[0]);
Boolean searchResult;
Either way this is my main, and im just trying to set args[0] as filename.
I am running my program like so:
? java SpellChecker >input.txt
So i guess it could be args[2] but i tried that and I'm still getting ArrayIndexOutOfBoundsException whenever i use any number in there O.o
I would appreciate any help.
THANKS!
Your way, java SpellChecker > input.txt means all outputs of your programs will be written in input.txt. That means if you do any kind of print, it will be written in input.txt.
The command you need is java SpellChecker input.txt
I want to return the same text that is returned when I manually type a command into the cmd prompt in Windows. Here is an example that does not work.
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
String g = "";
Runtime.getRuntime().exec(new String[] {"ipconfig", g});
System.out.println(g);
}
}
I don't know if I should be looking into Runtime.getRuntime()exec because the way I understand the api ( http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Runtime.html ) is that of all of the exec examples, none return a string. The return value (if I understand right) on some is actually a 'process' which I can only guess means nothing gets returned, but the process is started. I used ipconfig in the example, but I actually need to run various diagnostic commands and analyze the string (which I have referred to as the 'cmd prompt').
To capture the output of the command, you can use this:
Process p = Runtime.getRuntime().exec(new String[] {"ipconfig", g});
InputStream s = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(s));
String temp;
while ((temp = in.readLine()) != null) {
System.out.println(temp);
}
Please not that the readLine() method will block until it reads an input or the process is terminated.
The Java String is immutable, meaning that the "" referenced by g will never change. No code that doesn't do an assignment of g will ever print something other than the empty string to System.out.
Rather than using Runtime.exec, I recommend you use the Commons-Exec library from the Apache Commons project. It provides a much more reliable means of executing external applications (passing the arguments reliably and preventing such things as an unread output stream locking up the program).
You can capture the command output using the PumpStreamHandler and an input stream of your choice.
If you look at the javadoc link you've already posted, you'll see that Runtime.exec() returns a Process object, and the Process class has a method getOutputStream() to get at the standard output stream of the new process.
I dont know how to describe it well, but i will try. Ok, i want to be able to build my java program so that when it opens, it will look and work exactly as it does in the console. So it reads the Scanner class and prints normally, and does everything it would do if it was in the console. Ive looked around for this and havent found anything. I can make a gui java program fairly easily, but i would rather have a terminal, console like program, that works exactly as the java console, thanks.
Based on your comment:
but i want to do hundreds of links at
a time which works perfectly using the
scanner nextLine() method, i can just
post 100 or 200 links in the java
console and it will automatically sort
them out.
I'm guessing what you want is batch processing. You can have your 100 or 200 links in a text file, one per line. And then your Java program:
import java.io.*;
public class Batch{
public static void main(String args[]){
try{
FileInputStream fstream = new FileInputStream("sample.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
while((line = br.readLine()) != null){
//Do something with your line
System.out.println(line);
}
in.close();
}catch(IOException ioe){
System.err.println(ioe.getMessage());
}
}
}
You compile this program, open up a console and run it:
java Batch
It reads your sample.txt file and for each line it does something, in this case print it to the console.
You might be looking for the standard input and output members of the java.lang.System class:
class HelloWorld {
public static void main(String... argv) {
System.out.println("Hello, World!");
}
}
For processing input, you can use Scanner on standard input:
Scanner scanner = new Scanner(System.in);
If you want to get really fancy, you can print some of your output to System.err, which is a PrintStream just like System.out.
From the comment, "when i compile my classes i get a jar file, which does nothing when i click on it, which i think is normal because its not gui," I think your problem is an operating system problem (Windows?), not a Java problem.
Windows maps the "Open" action for JAR files to run with javaw.exe, which doesn't create a console. You'll either need to modify the default file association on each machine, or create something like a batch file that overrides this default behavior.
You could write two programs: the first is your actual "console" Java application, and another is just a shell that uses Runtime.exec() to create a Windows console (cmd) and executes the first program within it.
There are also opensource projects (check Sourceforge) that wrap your JAR in a Windows executable.
Use launch4j. It will create a exe of your non GUI application. In launch4j go to header section and check the console option. Done!