Read filename from command line argument - java

I have in my code a hardcoded name for a text file I am reading.
String fileName = "test.txt";
However I now have to use a command argument like so:
text.java arg1 arg2 arg3 (can be any amount) < test.txt
Can anyone help me please?
I have it getting the arguments no problem just not sure on the file. Thank you
I have tried:
String x = null;
try {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
while( (x = f.readLine()) != null )
{
System.out.println(x);
}
}
catch (IOException e) {e.printStackTrace();}
System.out.println(x);
}
However my application now hangs on readLine, any ideas for me to try please?

That is because the file is not passed as an argument, but piped as standard input.
If that is the intended use (to pipe the content of the file), then you just have to read it from System.in (in means standard input):
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String firstLine = in.readLine();
// etc.
}
If you just wanted to pass the file name, then you have to remove or escape that <, because it means "pipe" in shell.

Pass the file as filename to your program and then open this file and read from it.

Related

Read a single line from text file & not the entire file (using buffered reader)

I am trying to write a piece of code that reads a single line of text from a text file in java using a buffered reader. For example, the code would output the single line from the text file and then you would type what it says and then it would output the next line and so on.
My code so far:
public class JavaApplication6 {
public static String scannedrap;
public static String scannedrapper;
public static void main(String[] args) throws FileNotFoundException, IOException {
File Tunes;
Tunes = new File("E:\\NEA/90sTunes.txt");
System.out.println("Ready? Y/N");
Scanner SnD;
SnD = new Scanner(System.in);
String QnA = SnD.nextLine();
if (QnA.equals("y") || QnA.equals("Y")) {
System.out.println("ok, starting game...\n");
try {
File f = new File("E:\\NEA/90sTunes.txt");
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
}
}
}
}
It outputs:
Ready? Y/N
y
ok, starting game...
(and then the whole text file)
But I wish to achieve something like this:
Ready? Y/N
y
ok, starting game...
(first line of file outputted)
please enter (the line outputted)
& then repeat this, going through every line in the text file until it reaches the end of the text file (where it would output something like "game complete")...
This would read the first line ".get(0)".
String line0 = Files.readAllLines(Paths.get("enter_file_name.txt")).get(0);
This block of code reads the whole file line by line, without stopping to ask for user input:
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
Consider adding a statement to the loop body that seeks some input from the user, like you did above when asking if they were ready ( you only need to add one line of code to the loop, like the line that assigns a value to QnA )

Converting a .java file to a .txt document

I am trying to figure out how to load a .java doc and out put it into a text document...
What needs to be done:
Write a program that opens a Java source file, adds line numbers, and
saves the result in a new file. Line numbers are numbers which
indicate the different lines of a source file, they are useful when
trying to draw someone's attention to a particular line (e.g.,
"there's a bug on line 4"). Your program should prompt the user to
enter a filename, open it, and then save each line to an output fix
with the line numbers prepended to the beginning of each line.
Afterward, display the name of the output file. The name of the output
file should based on the input file with the '.' replaced by a '_',
and ".txt" added to the end. (Hint: if you are using a PrintWriter
object called pw to save the text file, then the line
"pw.printf("%03d", x);" will display an integer x padded to three
digits with leading zeros.)
The text.java needs to output into the text document with numbered lines such as:
001 public class dogHouse {
002 public static void main (String[] args) {
003 and so on...
004
import java.io.*;
public class dogHouse {
public static void main(String [] args) throws IOException {
// The name of the file to open.
String fileName = "test.java";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
// The name of the file to open.
finally {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// Note that write() does not automatically
// append a newline character.
bufferedWriter.write("Hello there,");
// Always close files.
bufferedWriter.close();
}
}
}
You need to print and count the line(s) as you read them. You also need to differentiate between your output file and your input file. And, I would prefer to use try-with-resources Statements. Something like,
String fileName = "test.java";
String outputFileName = String.format("%s.txt", fileName.replace('.', '_'));
try (BufferedReader br = new BufferedReader(new FileReader(fileName));
PrintWriter pw = new PrintWriter(new FileWriter(outputFileName))) {
int count = 1;
String line;
while ((line = br.readLine()) != null) {
pw.printf("%03d %s%n", count, line);
count++;
}
} catch (Exception e) {
e.printStackTrace();
}

Reading file passed in cmd

i have problem which is probably easy but in can't figure it out. I'm writing simple java program called task1 to read a file and calculate some values. I run this program in cmd like this:
cmd: java task1 calculate
Word "calculate" after "task1" is an argument which start my method to calculate some values. But i would like to calculate some values in a file called values.txt. My problem is that i don't know how to write my code to that read file. This file is passed as argument in cmd like that:
cmd: java task1 calculate < values.txt
hope, you can understand my problem. It Would be awesome if you can just tell me how to print this values in my file
if(args.length == 0)
{
System.out.println("Insert some arguments");
}
else if(args[0].equals("calculate"))
{
//here i would like to read my file (values.txt)
}
I appreciate your help and i am sorry for my bad English.
You should use buffered reader for that.
When you do
cmd: java task1 calculate < values.txt
you pass the contents of values.txt in the program as standard input.
The code would look like this
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line = bufferedReader.readLine();
This way you read a line with BufferedReader.
For more please consult http://alvinalexander.com/java/java-bufferedreader-readline-string-examples
PS: It is also possible to directly read a file from disk, no need to pipe it to the program.
You do that like this:
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
You can try Files#readAllLines(). This will read a text file and store every line in
a List collection:
//Path valuesPath = Paths.get("VALUES_DIR", "values.txt");
Path valuesPath = Paths.get("./" + args[0]);
try {
List<String> lines = Files.readAllLines(valuesPath, Charset.defaultCharset()));
for (String line : lines) { //print lines (or do whatever you need)
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Where args[0] is the name of the file to read (on the same directory where the task1.jar is).
Call your java program as:
java -jar task1.jar values.txt
EDIT:
To read piped file as standard in:
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) { //print lines (or do whatever you need)
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
call your task as:
java task1 calculate < VALUES_PATH\values.txt
Where VALUES_PATH is the complete path where your file is.
Note that when you use < then you can't get back the command line in your own program.

User Input File Console/Command Line - Java

Most examples out there on the web for inputting a file in Java refer to a fixed path:
File file = new File("myfile.txt");
What about a user input file from the console? Let's say I want the user to enter a file:
System.out.println("Enter a file to read: ");
What options do I have (using as little code as possible) to read in a user specified file for processing. Once I have the file, I can convert to string, etc... I'm thinking it has to do with BufferedReader, Scanner, FileInputStream, DataInputStream, etc... I'm just not sure how to use these in conjunction to get the most efficient method.
I am a beginner, so I might well be missing something easy. But I have been messing with this for a while now to no avail.
Thanks in advance.
To have the user enter a file name, there are several possibilities:
As a command line argument.
public static void main(String[] args) {
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
}
By asking the user to type it in:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
Use a java.io.BufferedReader
String readLine = "";
try {
BufferedReader br = new BufferedReader(new FileReader( <the filename> ));
while ((readLine = br.readLine()) != null) {
System.out.println(readLine);
} // end while
} // end try
catch (IOException e) {
System.err.println("Error Happened: " + e);
}
And fill the while loop with your data processing.
Regards,
Stéphane

Passing a file as a command line argument and reading its lines

this is the code that i have found in the internet for reading the lines of a file and also I use eclipse and I passed the name of files as SanShin.txt in its argument field. but it will print :
Error: textfile.txt (The system cannot find the file specified)
Code:
public class Zip {
public static void main(String[] args){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
please help me why it prints this error.
thanks
...
// command line parameter
if(argv.length != 1) {
System.err.println("Invalid command line, exactly one argument required");
System.exit(1);
}
try {
FileInputStream fstream = new FileInputStream(argv[0]);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the object of DataInputStream
...
> java -cp ... Zip \path\to\test.file
When you just specify "textfile.txt" the operating system will look in the program's working directory for that file.
You can specify the absolute path to the file with something like new FileInputStream("C:\\full\\path\\to\\file.txt")
Also if you want to know the directory your program is running in, try this:
System.out.println(new File(".").getAbsolutePath())
Your new FileInputStream("textfile.txt") is correct. If it's throwing that exception, there is no textfile.txt in the current directory when you run the program. Are you sure the file's name isn't actually testfile.txt (note the s, not x, in the third position).
Off-topic: But your earlier deleted question asked how to read a file line by line (I didn't think you needed to delete it, FWIW). On the assumption you're still a beginner and getting the hang of things, a pointer: You probably don't want to be using FileInputStream, which is for binary files, but instead use the Reader set of interfaces/classes in java.io (including FileReader). Also, whenever possible, declare your variables using the interface, even when initializing them to a specific class, so for instance, Reader r = new FileReader("textfile.txt") (rather than FileReader r = ...).

Categories

Resources