pass command line arguments to copy a file name in Java - java

Is it possible to write a program from an IDE (such as NetBeans or Eclipse) that can compile from the command line and run once the user enters two arguments just after the name of the java class program to run?
If so, can an absolute path be passed in as one of the arguments?
And if so, (if the source or destination file has a multi-word descriptor, like Big Sky File.txt), how can it be passed in as an argument?
I know this is a lot of questioning, but I have searched high and low and nothing seems to so much as scratch the surface on any of these topics.
#Code-Guru, #thkala, here's the code I am attempting (took a bit to format):
edit: #Code-Guru, I have added the offending line (not sure how I missed that).
next edit: # Code-Guru, here is the updated file contents from CopyFile.java, and the resulting error message:
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException, NullPointerException
{
int num;
FileInputStream fileIn;
FileOutputStream fileOut;
try
{
// open input file
try
{
fileIn = new FileInputStream(args[0]);
}
catch(FileNotFoundException e)
{
System.out.println("Input File Not Found.");
return;
}
// open output file
try
{
fileOut = new FileOutputStream(args[1]);
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening Output File.");
return;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Incorrect argument use:java CopyFile Source Destination");
return;
}
// Copy File
try
{
do
{
num = fileIn.read();
if(num != -1)
{
fileOut.write(num);
}
}
while(num != -1);
}
catch(IOException e)
{
System.out.println("File Error: Could not copy file.");
}
fileIn.close();
fileOut.close();
}
}
Here is the error message I receive from the command prompt:
Error: Could not find or load main class CopyFile

Is it possible to write a program from an IDE (such as NetBeans or Eclipse) that can compile from the command line and run once the user enters two arguments just after the name of the java class program to run?
Yes, it is possible.
If so, can an absolute path be passed in as one of the arguments?
Definitely - any string can be passed as an argument, as long as its size does not exceed a certain (usually system-defined) limit.
And if so, (if the source or destination file has a multi-word descriptor, like Big Sky File.txt), how can it be passed in as an argument?
Typically, arguments with spaces, special characters e.t.c. are handled by the calling shell, rather than the Java program. Consult your documentation on how to properly quote such arguments in whatever command line shell you are using.

The answer lies in this part of the error message:
(wrong name: copyfile/CopyFile)
I.e., your class's fully qualified name is copyfile.CopyFile. Java requires that the package layout match the folder layout on disk so it knows how to find things.
So either your class file must be in a subfolder called copyfile, and then invoked as java copyfile.CopyFile, or you can compile your class in the unnamed default package by removing the package copyfile; declaration from the code (you haven't shown that line, but it must be there).
More info: http://www.jarticles.com/package/package_eng.html

Related

How to get File name from cmd argument to create a copy?

I'm working on a program that reads from a file with a custom extension I made. The idea is that an error report is created every time a file is read. The error report must be in whatever folder the source file was called from. The error file is a copy of the source file, but it has a line number at the beginning of each line and indicates at the end of the line if an error occurred at that line.
(I'm not trying to set up the numbering on this question, this question is just about creating the copy)
So for example, when I call my program from the command prompt:
C:\MyLocation>java =jar myJavaProgram.jar myFileToRead.CustomExtension
Asides from reading the file, it should also create a copy at the same location called myFileToRead-ErrorReport.txt
Additionally: If the source file has no extension, I have to assume that it's still the correct extension, so there won't always be a '.myCustomExtension' segment to replace into .txt
The problem is that I don't know how to grab the file name, because it's coming from the args list of the main method. I am using the following to read the file
public static void main(String[] args) throws FileNotFoundException {
try{
File inputFile = new File(args[0]);
Scanner sc = new Scanner(inputFile);
while(sc.hasNext()){
System.out.println(sc.nextLine());
}
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
System.out.println("File not found.");
}
}
So how can I get that file name to make something like
File errorReport = new File("./" + inputFileName + ".txt"); ?
First the code. The explanations appear after the code.
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("ERROR: Missing filename argument.");
}
else {
String filename = args[0];
if (filename.length() == 0) {
System.out.println("ERROR: Empty filename argument.");
}
else {
if (!filename.endsWith(".CustomExtension")) {
filename += ".CustomExtension";
}
String name = filename.substring(0, filename.indexOf(".CustomExtension"));
name += "-ErrorReport.txt";
File inputFile = new File(filename);
File directory = inputFile.getParentFile();
File errorReport = new File(directory, name);
System.out.println(errorReport.getAbsolutePath());
}
}
}
I make it a habit of checking the parameters. Hence I first check that the file name was supplied. If it was, then I check that it is not an empty string. Note that I have omitted some checks, for example checking whether the named file exists and is readable.
You wrote in your question that the file name argument may or may not include the .CustomExtension. Hence I check whether the supplied name ends with the required extension and append it if necessary. Now, since I know what the file name ends with, that means that the required part of the name is everything up to the extension and that's what the call to substring() gives me.
Once I have the required name, I just append the part that you want to append, i.e. -ErrorReport.txt.
Method getParentFile() in class java.io.File returns the directory that the file is located in. Hence I have the directory that the input file is in. Finally I can create the error report file in the same directory as the input file and with the desired file name. For that I use the constructor of class java.io.File that takes two parameters. Read the javadoc for details.
Note that creating a File object does not create the file. Creating an object to write to the file does, for example FileWriter or OutputStreamWriter.
Here is the code example to create a file, with filename passed from cmd line as argument and to get the same file name :
Class Demo{
public static void main(String[]args){
String path ="<path of file>"
String name= args[0];
File f = new File(path+name+".txt");
f.createNewFile(); //create file
System.out.println(f.getName()); // will give you the file name
}
}
cmd line : java -cp . Demo.java <filename>
Note : '.' used in the cmd if your class file is present in current dir
You can refer the code and modify to suit your requirement.
Hope this is what you are looking for.

Error: [filename].txt (No such file or directory) when trying to read in a txt file in Java (Ubuntu cmd line)

So I'm writing a piece of code that reads in many addresses and then manipulates the data, line by line, then adds it to a Binary Search Tree. However, the file isn't being found no matter what I try. I know the txt file needs to be in the root directory, but (I'm a student) we're required to submit a .tar.gz containing the contents of a directory made specifically for the assignment so I suppose it needs to be in the submitted folder.
I've tried using the "normal" methods I used in IDEs, but they all return the same error.
My code (roughly - obviously you don't really need to see the BST/manipulation stuff), right now, but I've tried every other typical file read-in method:
import java.io.InputStream;
import java.io.*;
import java.util.Scanner;
public class PrintIt{
public static void main(String args[]){
try{
File inFile = new File("/bin/testdata.txt");
Scanner sc = new Scanner(inFile);
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line); //manipulation in place of this
}
sc.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
I really only need the reading in the file part - the BST stuff/manipulation is just for context, just in case it mattered/there's a better way than reading through each line of the file and adding each to the Tree.

checking files as command line arguments in java

I'm trying to pass in a text file(input and output files) as the command line arguments inside a try-catch block.
This is a snippet of the code:
try {
PrintWriter outFile = new PrintWriter(new FileOutputStream(args[0]));
} catch (FileNotFoundException exc) {
System.out.println("file does not exist");
} catch (Exception e) {
System.out.println("general exception");
}
I'm trying to check it by passing a file that doesn't exist but it doesn't seem to work, not even in the general exception. I tried printStream as well but nothing really changed.
Any help would be appreciated, thanks!
First create a file from text
File inputFile = new File(args[0]);
Now check the existence of file using inputFile.exists() which will give you boolean result true if file exists or false if doesn't
Plus you also wanna put a check for directories too because inputFile.exists() also return true if the input Path is of a directory (Folder)
so your check will look like
if(inputFile.exists() && ! inputFile.isDirectory()) // ! mean not/complement operator
{
// yes it's a file
}
Why complement ? cuz we wanna only go further if input represents a file not directory

Using Java's File class and how to gain correct access permissions to create files

bellow is the code of a house cleaning function i have written, the function is supposed to check for a files existance, if it is not there it then creates the file and adds some data to it.
However when i check that i have read and write permisions using the file.canRead() and file.canWrite() these both return false when checked however the program should have access to the file path where specified.
public void HouseCleaning()
{
//inform the user that the file is not available
System.out.println("According the the checks we have run, the current system you are on we do not have the required files set up");
System.out.println("...");
//create info.txt
try
{
File file = new File("C:\\GameCounter\\info.txt");
System.out.println(file.canRead());
System.out.println(file.canWrite());
if(file.canRead() && file.canWrite())
{
//then we can create the file
System.out.println("we can do this");
if(!file.exists())
{
//file does not exist
if(file.createNewFile())
{
//file has been created
System.out.println("File has been successfully created!");
PrintWriter writer = new PrintWriter("C:\\GameCounter\\info.txt", "UTF-8");
writer.println("Info File:");
writer.flush();
writer.close();
}
else
{
//file has not been created!
System.out.println("for some reason the file cannot be created!");
}
}
else
{
//file must already exist? so check for other required ones!
}
}
else
{
System.out.println("we require extre permissions!");
}
}
catch(Exception e)
{
//error has been thrown
System.out.println(e);
}
}
So my question is firstly is that theoretically if the code bellow is correct then it is permissions on the hard disk itself then? if the code is not correct please do correct me.
Many Thanks for any help regarding this.
I suggest you change your program and use the advantages Javas Exception Handling has to offer.
private final static String COUNTER = "C:\\GameCounter\\info.txt";
public static void main(String[] args) {
File file = new File(COUNTER);
if (!file.exists()) {
try {
PrintWriter writer = new PrintWriter(COUNTER, "UTF-8");
writer.println("Info File:");
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/// ... more to come
}
This is a lot shorter and you have to take care of the exceptions anyway. If the file can not be written to (In my test I simply created it and assigned the readonly attribute) you will receive an according exception:
java.io.FileNotFoundException: C:\GameCounter\info.txt (Access denied)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
at java.io.PrintWriter.<init>(PrintWriter.java:192)
at java.io.PrintWriter.<init>(PrintWriter.java:232)
at xyz.main(xyz.java:12)
In my example I only dump the exception to the screen. In a real life scenario you need to react on the exception and perhaps re-throw a exception you defined on your own.
The methods canRead and canWrite return false if the file does not exist.
Quote from the documentation (canRead):
Returns:
true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise
and (canWrite):
Returns:
true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
The reason the file.canRead() file.canWrite() return false are most likely because you have not created the files.
Java Doc
public boolean canRead() Tests whether the application can
read the file denoted by this abstract pathname.
The method calls return true when you create the files first.
Remember, File is a representation of a system file, simply creating an instance of the File object will not create a file

FileNotFoundException - Reading a text file in java

I'm getting a file not found exception from this code even though it's within the try catch statement and I'm not sure what's wrong, the file is within the project folder and is called 'someFile.txt'. This is the main method:
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("no arguments given");
return;
}
double FRE = sortFile(args[0]);
System.out.println("Readability of file " + args[0] + "= " + FRE);
}
And this is the sortFile method where the exception occurs:
public static double sortFile(String FileName) {
int nWords = 0;
int nSyllables = 0;
int nSentences = 0;
File text = new File(FileName);
try {
Scanner sc = new Scanner(text);
while (sc.hasNext()) {
contents.add(sc.next());
++nWords;
}
sc.close();
for (String e : contents) {
getNumSyllables(e);
}
} catch (FileNotFoundException e) {
System.out.println("The file" + FileName + "could not be opened.");
e.printStackTrace();
}
double FRE = getFRE(nWords, nSyllables, nSentences);
return FRE;
}
Thanks for any help :)
well, the file does not exist in that location. Try to add
System.out.println(text.getAbsolutePath())
to see where the file is expected. Note, when you provide a relative path (e.g. some/path/filename.ext), this is relative to the working directory. The working directory is the folder your java program is started in.
If you're using an IDE (e.g. Eclipse, IntelliJ, Netbeans) you can define the working directory in your run configuration.
See:
Javadoc of java.io.File to learn how relative paths work inside a Java environment: http://docs.oracle.com/javase/7/docs/api/java/io/File.html
working dir: Getting the Current Working Directory in Java
I'm getting a file not found exception from this code even though it's
within the try catch statement
The try-catch does not prevent the Exception from being thrown. It merely executes the code in the catch block when an Exception is thrown, and you are just printing the stack trace in the catch block, which is what usually printed anyways on uncaught exceptions.
To resolve your actual issue, first try passing the full path to the file, verify that it works and then use Tim's answer to debug your absolute path.
Try launching your program with the absolute path.
java yourclassname absolutepath_to_someFile.txt

Categories