Data reading from file, file name pass through Commandline argument in java - 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

Related

In Java, how do I find the proper path to open a txt file that's name is provided as a command line arguement?

I'm working on a program that is supposed to take two files as command line arguments, open the files, and read data from the files to make a data structure.
So far, I have been able to make the structure using File() to open the files and Scanner to read the data. The problem is that I have been providing a specific path to the call for File like this
File f1 = new File("F:/MinSpan/resources/cities.txt");
Scanner sc1 = new Scanner(f1);
I don't think this is going to work for the person who tries to run this program, because I have provided the path for where my specific txt files are located - they're on my flash drive (F) and in some folders. Is there a way I can program this to pass some kind of args[] value in for File() based on the cmd arguement the user has provided?
I have already tried just doing new File(args[2]) , and it can't find the file because there is no path.
The reason for that is because, if you are passing in only two paths, args[2] wont return anything, because args[] starts at 0. So you'd want to use:
new File(args[0]);
new File(args[1]);
Does that make sense?
If you're going for something like java -jar program.jar FILE, then have the program check for the String in args[] at index 0.
Then, construct your file. Check if the file exists (in java.io, it's File.exists()) and return an error message to the user if it's wrong.

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.

reading from external txt file from jar file

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

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.

Error in reading from file (Java)

I posted a similar question here: Read from a file containing integers - java but couldn't get a decent reply.
Now I have written this new code which only reads a file and outputs the result.
I get a FileNotFoundException whenever I try to read from a file. The code is below:
import java.io.*;
public class second {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\Haroon\\workspace\\ppp\\temperature.txt");
FileReader file = new FileReader(f);
BufferedReader buf = new BufferedReader(file);
String s = null;
while((s = buf.readLine()) != null){
System.out.println(s);
}
}
}
This is strange because the file is in the project's folder.
Any help would be appreciated.
That should work. Go to the location of the file, copy the path, paste it in your code, and escape the slashes. You are missing something.
Also check that the name/extension of the file is correct, you could have something like "temperature.txt.txt".
I don't know why you are unable to read the file. Its working fine on my system. Since you are making you project in eclipse. I will post a workaround here.
System.out.println(System.getProperty("user.dir"));
Use this command to find the current user directory at the time of execution. Now directly place the file in that user directory. Now you can directly read the file just by its name.
For eg:
File f = new File("temperature.txt");
Also as mentioned by 'lxxx' do check the file name and the extension by enabling show file extension option in Windows.

Categories