Inputting file name through main function argument (args[0]) - java

EDIT: to run my code i am using "java filename.java input1.txt" is this correct?
I am creating a program where i have to tokenize a string into separate words and that string is in a text file. I have to specify the text file name in the terminal through command line arguments (args[0], etc). I am able to scan and print the content of the text file if i specify through paths but when i try to do it using args[0] it doesn't seem to work. I am using net beans. I will attach my section of code here:
public static void main(String[] args) {
try {
File f = new File(args[0]);
//using this commented out section using paths works File f = new
//File("NetBeansProjects/SentenceUtils/src/input1.txt");
Scanner input = new Scanner(new FileInputStream(f));
while(input.hasNext()) {
String s = input.next();
System.out.println(s);
}
} catch(FileNotFoundException fnfe) {
System.out.println("File not found");
}
SentenceUtils s = new SentenceUtils();
}

java filename.java input1.txt
is not correct for running a java program, you need to compile the *.java file to get a *.class file which you can then run like:
java filename input1.txt
assuming your class is in the default package and you are running the command in the output directory of your compile command, or using the fully qualified class name of the class, i.e. including the package name. For example if your class is in the package foo/bar/baz (sub folders in your source folder) and has the package declaration package foo.bar.baz;, then you need to specify your class like this:
java [-cp your-classpath] foo.bar.baz.filename input1.txt
for input1.txt to be found it has to be in the same directory where you run the command.
your-classpath is a list of directories separated by a system dependent delimiter (; for windows, : for linux, ...) or archives which the java command uses to look up the class to run specified and its dependencies.
NetBeansProjects/SentenceUtils/src/input1.txt is a relative path.
File f = new File("NetBeansProjects/SentenceUtils/src/input1.txt");
if this works then it means that the current working directory (i.e. the directory from which all relative paths are calculated) is the the rectory named NetBeansProjects.
You get FileNotFoundException because your file is expected to be in
NetBeansProjects/input1.txt
To find out which is the current working directory for your running program you can add the following statement:
System.out.println(new File("").getAbsolutePath());
Place input.txt in that directory and it will be found.
Alternatively you can pass the absolute path of your input file. an absolute path is a path that can be used to locate your file from whatever location your program is running from on your local filesystem. For example:
java -cp <your-classpath> <fully-qualified-name-of-class> /home/john/myfiles/myprogects/...../input1.txt
To sum up, what you need to know/do is the following:
the location of your program class and its package (filename)
the location of your input file (input.txt)
pass the correct argument accordingly

Related

Java File Reading: Have to enter full path

package files;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class file {
public static void main(String[] args)throws FileNotFoundException {
File file = new File("txtfile.txt");
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
System.out.println(input.nextLine());
}
}
}
Where it says file.txt I have to enter the full file path. All tutorials I watch do not have to do this.
Yeah! File file = new File("txtfile.txt"); txtfile.txt is a path to your file that you want to read. Provide the path where file is like "C:\Users\me\Desktop\txtfile.txt" if the file is not in the same directory where your java file is. After you compile the java file a .class file is created it that .class file is also created in the same folder it will work with.
File file = new File("txtfile.txt"); and you don't need to specify the full path.
If not you then you have to provide the absolute file path like above.
If you don't enter the path it won't compile and show error.
To set a path..
Open the command prompt and it show something like this
C:user>admin
You need to change it and point it your program saved location (use cd for change it)
Then type path="
And go to localdisc C: and open programfile->java->jdk->bin
Then save the path at above
Which is something like c:/programfile/java/jdk1. 0./bin
Save and copy it in front of path="c:/programfile/java/jdk1. 0./bin";
Then press enter
Then compile the program using javac filename. Java
And run using java filename

How to create executable file in Java using Netbeans

I made a cache simulator program for a homework, I decided to use java. I want to create an executable jar file that will work on any system, but the problem is that my program gathers data from an external text file. How can I include that text file inside the jar so that there won't be any problem when executing file? By the way, I am using NetBeans IDE.
If you don't need to write to the file, copy into the src directory. You will no longer be able to access like a File, but instead will need to use Class#getResource, passing it the path from the top of the source tree to where the file is stored.
For example, if you put it in src/data, then you'd need to use getClass().getResource("/data/..."), passing it what ever name the file is...
Clean and build...
Yes and I said Yes. To really make your jarfiles along with the text files. Please ensure that links to the folder on which the text files is where properly coded and well linked.
The three Examplary Method below should get you working irrespective of any IDEs. Please rate this and give me a shout if you still need further help.......Sectona
Method 1
Step 1:- Locate your folder that contain your java file by using cd command.
Step 2:- Once your enter your folder location then view your java file by dir
command.
Step 3:- Compile your java file using
javac file.java
Step 4:- view class file by type dir command.
Step 5:- Now you want to create a manifest file.
I)Go to folder<br>
II)Right-click->New->Text Document
III)open text document. Type main class name ,
Main-Class: main-class-name
IV)Save this file your wish like MyManifest.txt
Step 6:- To create executable jar file type
jar cfm JarFileName.jar MyManifest.txt JavaFike1.class JavaFile2.class
Step 7:- Now you see the Executable jar file on your folder. Click the file to
Run.
Step 8:- To run this file via command prompt then type
java -jar JarFileName.jar
Step 9:- You done this..........Sectona
Method 2
The basic format of the command for creating a JAR file is:
jar cf jar-file input-file(s)
The options and arguments used in this command are:
The c option indicates that you want to create a JAR file.
The f option indicates that you want the output to go to a file rather than to stdout.
jar-file is the name that you want the resulting JAR file to have. You can use any filename for a JAR file. By convention, JAR filenames are given a .jar extension, though this is not required.
The input-file(s) argument is a space-separated list of one or more files that you want to include in your JAR file. The input-file(s) argument can contain the wildcard * symbol. If any of the "input-files" are directories, the contents of those directories are added to the JAR archive recursively.
Method 3
import java.io.*;
import java.util.jar.*;
public class CreateJar {
public static int buffer = 10240;
protected void createJarArchive(File jarFile, File[] listFiles) {
try {
byte b[] = new byte[buffer];
FileOutputStream fout = new FileOutputStream(jarFile);
JarOutputStream out = new JarOutputStream(fout, new Manifest());
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i] == null || !listFiles[i].exists()|| listFiles[i].isDirectory())
System.out.println();
JarEntry addFiles = new JarEntry(listFiles[i].getName());
addFiles.setTime(listFiles[i].lastModified());
out.putNextEntry(addFiles);
FileInputStream fin = new FileInputStream(listFiles[i]);
while (true) {
int len = fin.read(b, 0, b.length);
if (len <= 0)
break;
out.write(b, 0, len);
}
fin.close();
}
out.close();
fout.close();
System.out.println("Jar File is created successfully.");
} catch (Exception ex) {}
}
public static void main(String[]args){
CreateJar jar=new CreateJar();
File folder = new File("C://Answers//Examples.txt");
File[] files = folder.listFiles();
File file=new File("C://Answers//Examples//Examples.jar");
jar.createJarArchive(file, files);
}
}
You can keep any file in classpath and read as class path resource. Sample code is given below.
InputStream in = this.getClass().getClassLoader().getResourceAsStream("yourinputFile.txt");
Your jar will be class path, that means you can keep your file in root folder of java source which will get added to jar file while building it.

java.io.FileNotFoundException (File not found) using Scanner. What's wrong in my code?

I've a .txt file ("file.txt") in my netbeans "/build/classes" directory.
In the same directory there is the .class file compiled for the following code:
try {
File f = new File("file.txt");
Scanner sc = new Scanner(f);
}
catch (IOException e) {
System.out.println(e);
}
Debugging the code (breakpoint in "Scanner sc ..") an exception is launched and the following is printed:
java.io.FileNotFoundException: file.txt (the system can't find the
specified file)
I also tried using "/file.txt" and "//file.txt" but same result.
Thank you in advance for any hint
If you just use new File("pathtofile") that path is relative to your current working directory, which is not at all necessarily where your class files are.
If you are sure that the file is somewhere on your classpath, you could use the following pattern instead:
URL path = ClassLoader.getSystemResource("file.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
The JVM will look for the file in the current working directory.
Where this is depends on your IDE settings (how your program is executed).
To figure out where it expects file.txt to be located, you could do
System.out.println(new File("."));
If it for instance outputs
/some/path/project/build
you should place file.txt in the build directory (or specify the proper path relative to the build directory).
Try:
File f = new File("./build/classes/file.txt");
Use "." to denote the current directory
String path = "./build/classes/file.txt";
File f = new File(path);
File Object loads, looking for match in its current directory.... which is Directly in Your project folder where your class files are loaded not in your source ..... put the file directly in the project folder

Reading .txt file from another directory

The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file

How to pass a text file as a argument?

Im trying to write a program to read a text file through args but when i run it, it always says the file can't be found even though i placed it inside the same folder as the main.java that im running.
Does anyone know the solution to my problem or a better way of reading a text file?
Do not use relative paths in java.io.File.
It will become relative to the current working directory which is dependent on the way how you run the application which in turn is not controllable from inside your application. It will only lead to portability trouble. If you run it from inside Eclipse, the path will be relative to /path/to/eclipse/workspace/projectname. If you run it from inside command console, it will be relative to currently opened folder (even though when you run the code by absolute path!). If you run it by doubleclicking the JAR, it will be relative to the root folder of the JAR. If you run it in a webserver, it will be relative to the /path/to/webserver/binaries. Etcetera.
Always use absolute paths in java.io.File, no excuses.
For best portability and less headache with absolute paths, just place the file in a path covered by the runtime classpath (or add its path to the runtime classpath). This way you can get the file by Class#getResource() or its content by Class#getResourceAsStream(). If it's in the same folder (package) as your current class, then it's already in the classpath. To access it, just do:
public MyClass() {
URL url = getClass().getResource("filename.txt");
File file = new File(url.getPath());
InputStream input = new FileInputStream(file);
// ...
}
or
public MyClass() {
InputStream input = getClass().getResourceAsStream("filename.txt");
// ...
}
Try giving an absolute path to the filename.
Also, post the code so that we can see what exactly you're trying.
When you are opening a file with a relative file name in Java (and in general) it opens it relative to the working directory.
you can find the current working directory of your process using
String workindDir = new File(".").getAbsoultePath()
Make sure you are running your program from the correct directory (or change the file name so that it will be relative to where you are running it from).
If you're using Eclipse (or a similar IDE), the problem arises from the fact that your program is run from a few directories above where the actual source is located. Try moving your file up a level or two in the project tree.
Check out this question for more detail.
The simplest solution is to create a new file, then see where the output file is. That is the correct place to put your input file into.
If you put the file and the class working with it under same package can you use this:
Class A {
void readFile (String fileName) {
Url tmp = A.class.getResource (fileName);
// Or Url tmp = this.getClass().getResource (fileName);
File tmpFile = File (tmp);
if (tmpFile.exists())
System.out.print("I found the file.")
}
}
It will help if you read about classloaders.
say I have a text file input.txt which is located on the desktop
and input.txt has the following content
i came
i saw
i left
and below is the java code for reading that text file
public class ReadInputFromTextFile {
public static void main(String[] args) throws Exception
{
File file = new File(
"/Users/viveksingh/desktop/input.txt");
BufferedReader br
= new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
output on the console:
i came
i saw
i left

Categories

Resources