Command line args from cmdline vs in IDE - java

The following code behaves as expected if I run this from the actual command line (i.e. javac ..., java XXX.java (args[0]) (args[1]).
However if I try to set the command line args through eclipse I get the "Error with input or output file" error, but if the cmd line args in eclipse lenght != 2 I also get the "Must specify input file...." so I know it is assigning them
Does anyone know what the deal is with this?
public class main {
public static Scanner fileScanner(String fName) throws FileNotFoundException {
return new Scanner(new FileInputStream(fName));
}
public static PrintStream printStream(String fName) throws FileNotFoundException {
return new PrintStream(new FileOutputStream(fName));
}
public static void main(String[] args) {
Scanner scan=null;
PrintStream out=null;
if(args.length != 2) {
System.out.println("Must specify input file & output file on cmd line");
System.exit(0);
}
try {
scan = fileScanner(args[0]);
out = printStream(args[1]);
} catch(FileNotFoundException e) {
System.out.println("Error with input or output file");
System.exit(0);
}

I tried you program, it works fine in eclipse when i give filename with complete path.
package so.ch1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class main {
/**
* #param args
*/
public static Scanner fileScanner(String fName) throws FileNotFoundException {
return new Scanner(new FileInputStream(fName));
}
public static PrintStream printStream(String fName) throws FileNotFoundException {
return new PrintStream(new FileOutputStream(fName));
}
public static void main(String[] args) {
Scanner scan=null;
PrintStream out=null;
if(args.length != 2) {
System.out.println("Must specify input file & output file on cmd line");
System.exit(0);
}
try {
scan = fileScanner(args[0]);
out = printStream(args[1]);
} catch(FileNotFoundException e) {
System.out.println("Error with input or output file");
System.exit(0);
}
}
}
Args given: F:/temp/abc.txt F:/temp/xyz.txt

Related

Java openInputFile method doesn't work

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static Scanner userScanner = new Scanner(System.in);
public static void main(String[] args) {
Scanner fileScanner = openInputFile();
if (fileScanner == null)
return;
fileScanner.nextLine();
while(fileScanner.hasNextLine()){
//handle input
}
fileScanner.close();
}
public static Scanner openInputFile() {
String filename;
Scanner scanner = null;
System.out.print("Enter the input filename: ");
filename = userScanner.nextLine();
File file = new File(filename);
try {
scanner = new Scanner(file);
} // end try
catch (FileNotFoundException fe) {
System.out.println("Can't open input file\n");
return null; // array of 0 elements
} // end catch
return scanner;
} // end openInputFile
}
I'm trying to open an input file using the following method but it prints "Can't open input file" every time. I double checked the spelling, the file is in the same directory. Am I doing anything wrong?

Why won't this code read the file?

I'm trying to create a program that reads from a file named Clients and then through a for loop writes to the console. Here's the code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import static java.lang.System.out;
class ShowOccupancy{
public static void main(String args[])
throws FileNotFoundException{
Scanner diskScanner =
new Scanner (new File("Clients"));
out.print("Room Number");
out.print("/t");
out.println("Guests");
for (int roomNum=0; roomNum<10; roomNum++)
{
out.print(roomNum);
out.print("/t");
out.print(diskScanner.nextInt());
}
diskScanner.close();
}
}
Here are the errors in the console:
Exception in thread "main" java.io.FileNotFoundException: Clients (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at ShowOccupancy.main(ShowOccupancy.java:11)
And I created a Clients file for the java project.
This is a sample of how to read text files, hope it helps.
public static void main(String[] args) {
try {
Scanner reader = new Scanner(new File("FILE-PATH-HERE/clients.txt"));
//Prints lines
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
//Prints tokens
/*
while (reader.hasNext()) {
System.out.println(reader.next());
}
*/
reader.close();
} catch (FileNotFoundException ex) {
//Print error
ex.printStackTrace();
}
}

Get line number from a file

How can I implement a method to return the line-number of the line currently being scanned from a file. I have two scanners, one for the file (fileScanner) and another for the line (lineScanner)
this is what I have, but I don't know if I need the linenumber in the constructor!
public TextFileScanner(String fileName) throws FileNotFoundException
{
this.fileScanner = new Scanner(new File(fileName));
this.lineScanner = new Scanner(this.fileScanner.nextLine());
this.lineNumber = 1;
}
and I need this method:
public int getLineNumber()
{
}
You can use just one Scanner object to read a file and reports the line numbers.
Here is a sample code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LineNumber {
public static void main(String [] args) throws FileNotFoundException {
System.out.printf("Test!\n");
File f = new File("test.txt");
Scanner fileScanner = new Scanner(f);
int lineNumber = 0;
while(fileScanner.hasNextLine()){
System.out.println(fileScanner.nextLine());
lineNumber++;
}
fileScanner.close();
System.out.printf("%d lines\n", lineNumber);
}
}
Now, if you want do this using an Object-Oriented Programming approach then you can do something like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileProcessor {
// Mark these field as private so the object won't get tainted from outside
private String fileName;
private File file;
/**
* Instantiates an object from the FileProcessor class
*
* #param fileName
*/
public FileProcessor(String fileName) {
this.fileName = fileName;
this.file = new File(fileName);
}
public int getLineNumbers() {
Scanner fileScanner = null;
try {
fileScanner = new Scanner(this.file);
} catch (FileNotFoundException e) {
System.out.printf("The file %s could not be found.\n",
this.file.getName());
}
int lines = 0;
while (fileScanner.hasNextLine()) {
lines++;
// Go to next line in file
fileScanner.nextLine();
}
fileScanner.close();
return lines;
}
/**
* Test our FileProcessor Class
*
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
FileProcessor fileProcessor = new FileProcessor("text.txt");
System.out.printf("%d lines\n", fileProcessor.getLineNumbers());
}
}
Prints the Current line number:
System.out.println("The line number is " + new Exception().getStackTrace()[0].getLineNumber());
Example:
public class LineNumberTest{
public static void main(String []args){
System.out.println("The line number is " + new Exception().getStackTrace()[0].getLineNumber());
}
}

Is there a way to make this Java program more interactive?

I have written the following very simple Java program to ask user enter a file name, then it will report the number of lines of this file to the standard output:
import java.io.*;
import java.util.*;
public class CountLine {
public static void main(String[] args)
{
// prompt the user to enter their file name
System.out.print("Please enter your file name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
fileName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the file name, " + fileName);
File file = new File("C:/Users/Will/Desktop/"+fileName);
Scanner scanner;
try {
scanner = new Scanner(file);
int count =0;
String currentLine;
while(scanner.hasNextLine())
{
currentLine=scanner.nextLine();
count++;
}
System.out.println("The number of lines in this file is "+count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("There is no such file");
e.printStackTrace();
}
}
}
It is working.I would be really thankful if experts could help me
see if there is anything that can be improved in this code fragment,
If the file is not found, the exception is caught in the outermost catch statement and print out the stack trace. However, I think it is not very user-friendly, is there a way if the file does not exist, then the whole process restarts from beginning?
Thanks in advance.
Get some Structure in your code:
public static void main(String[] args)
{
string output;
string fname = readFileName();
if (fileValid(fname)) //Ensure FileExists
{
int lineCount = scaneFile(fname);
output = "some output text including line numbers"
}
else
{
output = "File Not Valid..."
}
//showOutput...
}
Obvious change is to make a method countLines(String filename) that contains most of the code currently in main(). Obviously main() will call countLines().
Prompting for a file could live in main() or another method.
To restart on error you need a loop like:
filename = // read filename from stdin;
while(keepGoing(filename)) { // null check or whatever to let you out of the loop
try {
int numLines = countLines(filename);
println("num lines in " + filename + "=" +numLines);
}
catch(Exception ex) { // or just specific excpetions
ex.printStackTrace();
}
}
Unless you want to make a GUI. I suggest you receive the path to the file as a command line parameter.
If file doesn't exist print a message and exit. That's all.
The command line will give the user the option to move up with the up-key, edit the name and run again.
This class is named LineCounter and is the "business logic"
package countlines;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
private int lineCount = 0;
public LineCounter(File file) throws IOException{
BufferedReader inFile = new BufferedReader(new FileReader(file));
while(inFile.readLine() != null) {
lineCount++;
}
inFile.close();
}
public int getLineCount() {
return lineCount;
}
}
This class is the "presentation logic"
package countlines;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main (String[] args){
if (args.length != 1){
System.out.println("Usage: java countlines/Main filePath");
System.exit(1);
}
File f = new File(args[0]);
if (!f.exists()){
System.out.println("File "+f.getAbsolutePath()+" doesn't exist");
System.exit(2);
}
if (f.isDirectory()){
System.out.println(f.getAbsolutePath()+" is a directory");
System.exit(2);
}
LineCounter c;
try {
c = new LineCounter(f);
System.out.println(c.getLineCount());
} catch (IOException e) {
System.out.println("Error reading file " + f.getAbsolutePath());
}
}
}

scanner class in java

Hey I'm trying to compile the following piece of code to basically read stuff from a file but it refuses to work. it gives me an java.io.FILENOTFOUNDEXCEPTION error at line4. help would be appreciated.
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) {
File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(fin);
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}
Try putting the absolute path to the file, like
c:\\java\\matrix1.txt or /home/user/java/matrix1.txt
=== OOPS
You need to catch the Exception that's being thrown. Here's a couple options:
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(fin);
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}
OR
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) {
File fin = new File ("matrix1.txt");
Scanner sc = null;
try {
scanner = new Scanner(fin);
}
catch(FileNotFoundException e) {
System.out.println("File does not exist...");
return;
}
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}
Make sure matrix1.txt is in your src folder if you're using Eclipse.
If you're using an IDE such as Netbeans/Eclipse, you need to put the file to be read in the project folder. This is usually 1 level above the src folder.
A good alternative in case you can't find the folder is to try and create a file. That way, you know where the file was created and you can place the file you want to read in that same folder.

Categories

Resources