reading from external txt file from jar file - java

I need that my program would support the operation :
java -jar filename.jar < input3.txt
I don't realy know how to deal with such command. How can I read the input file in my main program?
I need to read the txt file line by line.

You have the answer for your question in this post.
The main method of your program has to be ready to accept the file path in its arguments (and do what it has to do with the file).
If the file path is the first argument, then you can access it through the first position of the arguments array.
public class MainClass {
public static void main(String[] args) {
String filePath = args[0];
}
}
To execute, you'll just have to do:
java -jar filename.jar input3.txt

I found a solution, i used the command
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for the input

Related

Is it possible to in put filename in Java before program running?

Usually we do this $java hashcounter then system can print what is the filename? and we input the filename. Or we can write the filename like input.txt directly in Java code.
If I don't know the filename. Is it possible to do this?
$java hashcounter filename
I use Java on Mac. And my program is hashcounter.java.
Yes you can!
So in the case of putting java hashcounter filename in the command prompt, you can get the filename argument by adding:
public static void main(String[] args) {
String filename = args[0];
}

execute java from php from different directory

I have linux server(Debian). I have java program(compiled) in directory (reza). I am trying to execute this java program from /var/www and through php script.
$com=shell_exec('java /reza/z');
When call in above format it dosent return any results or execute java program.
When I call one php script in reza folder with same call format it returns correct response:
$com=shell_exec('php /reza/a.php');
Any idea how to make this to work correctlly?
P.S. when call java from same directory from php it returns correct response:
$com=shell_exec('java z');
Java file is compiled and include class file too.
Java sample code is:
import java.io.*;
public class z{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
fr.close();
}
}
Regards,
Finally solved this. Must change permission of target folder and enable "Write" too. Thanks all for helping me.
Use the classpath switch:
$com=shell_exec('java -cp /reza z');
Put the full path to Java executible in command (/usr/bin/java for example) . You may also need to set up class path etc with arguments. Remember that Java is executing in the context of the web server user, not your personal login, so the environment may not have the same variables defined with same values, such as JRE_HOME, PATH etc.
To find out what you have shell exec the env command to list the available environment variables, with php. I think phpinfo() will give you the same info.

Using files as arguments for a Java program in the terminal

java someJavaProgram fsa.fsa <test.txt
That, apparently, is a legitimate command to take with two files as arguments for a Java program in the terminal - one to read in, and then the other (and I think the idea is that it prints the output to the terminal directly). someJavaProgram, fsa.fsa and test.txt are all files in the same directory (being someProject/src, and someJavaProgram in the default package).
However, the response I am given in the terminal just says:
FSA file not found - please scan in the appropriate file.
Testing file not found, please scan in the new relevant file.
My question is two-fold:
What is this command and what is it for?
Does it need refining or modifying or is it the program that needs improvement?
I should note that I wrote the code in Eclipse, where I simply hardcoded filepaths into the program. I'm not sure if that affects anything but it's related.
EDIT: The filepaths and related code are as follows:
private static final String FILE_PATH = "src/test.txt";
private static final String FSA_PATH = "src/fsa1.fsa";
...
public static void main(String[] args) throws FileNotFoundException {
interpretAutomaton();
testAutomaton();
}
...
interpretAutomaton() {
...
Scanner fsaScanner = new Scanner(new BufferedReader(new FileReader(FSA_PATH)));
...
testAutomaton() {
...
Scanner fileScanner = new Scanner(new BufferedReader(new FileReader(FILE_PATH)));
*Both are surrounded by try/catch blocks - which clearly work!
Thanks to anyone who can help clarify on the matter!
Based on the comments so far, to answer your actual questions:
1) The command has four elements:
java - execute the java program
someJavaProgram - the name of the Java class to execute
fsa.fsa - the first argument to the java program, accessible via argv[]
<test.txt - standard input redirection, the contents of the file will be available on the program's standard input, ie. System.in
The net effect is to run your Java program with one argument and one file's contents on the standard input.
2) Both the command line and the program look like they need to change:
change the command line to:
java someJavaProgram fsa.fsa test.txt
That is, remove the <. You will also need to check the paths to the files are correct. This command line assume you are in the same directory as the files when you execute it.
Change your code to use the filenames on the command line rather than the hard-coded names.

Data reading from file, file name pass through Commandline argument in java

I have a .txt file assume it name My. I need to read this file content.I pass the file through command Line argument. What should I do in the Command prompt to pass the file to args[] array. Please help..............
You can get the file name with command line arguments:
java -jar myapp.jar abc.txt
or
java a.b.c.MyApplication abc.txt
will place abc.txt into args[0] of
public static void main(String[] args)
Then you can open the File and read it from Java code.
If you want the file contents (and not write Java code to read them), you could get them via System.in:
java -jar myapp.jar < abc.txt
(the above depends a bit on what kind of shell and OS you are using)
InputStream data = System.in;
Sometimes it's difficult to know where to start, but this question in its parts has been answered many times. However, perhaps to help you, it's best to point you in the right direction.
The steps you want are:
1) Get the String which represents the files path from the args array, perhaps something like:
String filePath = args[0];
However, you will want to also check that there is an item in the args to prevent the possibility of getting an exception when reading from the args (if nothing was passed from the command line) e.g:
String filePath;
if(args.length > 0){
filePath = args[0];
}else{
// do something to handle the error, probably exit the program?
}
For any more details on this, see here: Link to java tutorial
2)
Then, you want to make a File object from that string using the File constructor. Link to javadoc
File inputFile = new File(filePath);
3)
Then you need to read that file, line by line. For that I will point you to another SO answer, as there are many ways to do this:
Reading from a file - SO question
Hope this helps.
this is the code you probably want
String path =arr[0]; //first approach
/*Scanner in = new Scanner(System.in);
System.out.println("Enter the path of the file..."); // whole block command second approac
String path = in.nextLine(); */
File file = new File(path);
//apply your logic i just did some reading and writing to a file
/*BufferedReader inputStream = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
PrintStream out = new PrintStream(new FileOutputStream("a.txt"));
while(true)
{
String line = inputStream.readLine();
if(line == null)
break;
else
out.println(line);
}
*/
if you use the first approach run the program as
java className path_of_file
In second approach it will ask you for file path at runtime then you can enter the path of the file. just run like java className

Java Text File I/O Location

I have looked at other threads on where Java looks for files, but I still find myself confused.
I have a program, created in Eclipse (Juno) as a java project. I have made no modifications to anything else, and only have a main class for now.
When the program runs, it takes three inputs: a number, and two strings. The first string is the name of the file it has to read input from, the second is the file it has to put output to.
If I pass in "input.txt" for the input string, and have a file called input.txt, where should it be for Java to find it? I have tried putting it in src, bin, and in the project root. Currently, I am trying to access the file as follows:
File input = new File(args[1]);
Where args[1] is the first string passed to the program at the start. When I do this, I get an error "java.io.FileNotFoundException: input.txt (The system cannot find the file specified)"
Where should I be putting the file so that Java can find it?
Here is the relevant code:
public class main {
public static int runs;
public static File input;
public static File output;
public static String line1;
public static String line2;
public static String line3;
public static String reactions;
/**
* #param args
*/
public static void main(String[] args){
if(args.length != 3)
System.out.println("Please provide 3 arguments.");
runs = Integer.parseInt(args[0]);
File input = new File(args[1]);
File output = new File(args[2]);
System.out.println(runs);
System.out.println(input);
try {
Scanner sc = new Scanner(input);
For questions like this, try using the getAbsolutePath() method:
File input = new File(args[1]);
System.out.println(input.getAbsolutePath());
This shows you where the file object thinks the file is. That's where you should put the file... or perhaps modify the input argument accordingly so the program looks for the file in the place where you want the file to be.
You just need to put that input file in root folder of your project.
UPDATE :
As you are using scanner to get user input. then hide the code which your are using for args ie command line arguments.
Scanner sc = new Scanner(input);
runs = sc.nextInt(); // This will store your input line
in = sc.next(); // This will store your input file name
out = sc.next(); // This will store your output file name
If file name is not absolute (does not start with / on *nix and C:\ on Windows), then it is looked in current working directory. Java program may get its current working directory using System.getProperty ("user.dir").
In Eclipse you should explicitly set the execution directory for a run configuration.
The directory used by default can depend on project configuration, packaging, output directory, etc. so it's best to either (a) use an absolute path (e.g., prefaced with a c:\ or / etc.) or (b) set it in the run config.

Categories