Java File Reading: Have to enter full path - java

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

Related

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

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

Paths for images and executables in a jar

I have created a java program in eclipse and I am now ready to export it as a jar. My program uses an image file and an executable file. When testing my program in eclipse I referred to these file with a full path, which I obviously cannot do for the jar. Therefore, I changed them like this:
public static final String DRIVERLOC = "./resources/IEDriverServer.exe";
//some other code
File file = new File(DRIVERLOC);
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
and
File pic = new File("./images/Open16.gif");
openButton = new JButton("Select the Text File", createImageIcon(pic.getAbsolutePath()));
I put the images and the resources and images directory in the same directory with the jar. Now for some reason when I run the jar the IEDriverServer works fine but the image does not work and the error is that it cannot find the image. I am confused since I cannot seems to tell the difference. I also used "images/Open16.gif" which did not work either. Why would one work but the other does not? What is the easiest way to fix this?
We do this exact same thing with Selenium Drivers.
What you need to do is take the executable file out of the jar and put it some where windows can run it. If you try and open a jar/zip in Windows Explorer and then double click the .exe inside of a jar/zip, windows will extract the file to a temp directory, and then run it. So do the same thing:
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TestClass {
public static void main (String[] args) throws IOException {
InputStream exeInputStream = TestClass.class.getClassLoader().getResourceAsStream("resources/IEDriverServer.exe");
File tempFile = new File("./temp/IEDriverServer.exe");
OutputStream exeOutputStream = new FileOutputStream(tempFile);
IOUtils.copy(exeInputStream, exeOutputStream);
// ./temp/IEDriverServer.exe will be a usable file now.
System.setProperty("webdriver.ie.driver", tempFile.getAbsolutePath());
}
}
Let's say you save the jar and make it run this main function by default.
Running C:\code\> java -jar TestClass.jar Will run the jar from the C:\code directory. It will create the executable at C:\code\temp\IEDriverServer.exe
With your path set to "./resources/IEDriverServer.exe" you are referring to a file on the hard drive "." which does not exist.
You need to get the path of your .jar-file.
You can do this by using
System.getProperty("java.class.path")
This can return multiple values, seperated by semi-colons. The first one should be the folder your jar is in.
You can also use
<AnyClass>.class.getProtectionDomain().getCodeSource().getLocation()
I hope this helps :)
EDIT:
// First, retrieve the java.class.path property. It returns the location of all jars /
// folders (the one that contains your jar and the location of all dependencies)
// In my test it returend a string with several locations split by a semi-colon, so we
// split it and only take the first argument
String jarLocation = System.getProperty("java.class.path").split(";")[0];
// Then we want to add that path to your ressource location
public static final String DRIVERLOC = jarLocation + "/resources/IEDriverServer.exe";
//some other code
File file = new File(DRIVERLOC);
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
You can read about this here.

Why isn't java finding my file

Trying to learn how to read text files in Java. I have placed the text file within the same folder as IdealWeight.java. Am I missing something here?
IdealWeight.java
package idealweight;
import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class IdealWeight
{
public static void main(String[] args)
{
Scanner fileIn = null; //Initializes fileIn to empty
try
{
fileIn = new Scanner
(
new FileInputStream
("Weights.txt")
);
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
}
}
You could also put the file in the classpath and then do this:
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("Weights.txt");
Just another idea.
The java file IO system does not look for the file in the same directory as the class, but in the "default" directory for the application. Any application you run has a directory that it regards as its default, and that's where it would attempt to open this file. Try putting a full pathname to the file.
Or put the file you want to read in a directory, and run the application from that directory (in a terminal window) with "java IdealWeight".
You need to put Weights.txt in your working directory, not in the directory with the source file. If you're using Eclipse or a similar IDE, the this is probably the project root. As per this answer, you can use this snippet to get the full path to your working directory:
System.out.println("Working Directory = " + System.getProperty("user.dir"));
Check the result of running that command, and that should tell you where to put your text file. Once you have the text file in the right place then the code you posted should work fine.

Scanner class java file not found

Scanner Class couldnt find the file
I use NetBeansIDE, and the test.txt is in the folder path: D:\netbeans project works\ReadFile\src\readfile\test.txt
in the same folder the readfile.java exsist.
the code is as below.
It generates file not found.
package readfile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) throws IOException , FileNotFoundException
{
Scanner scanner = new Scanner(new File("test.txt"));
while (scanner.hasNextLine())
System.out.println(scanner.nextLine());
}
}
output:-
run:
Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.util.Scanner.<init>(Scanner.java:636)
at readfile.ReadFile.main(ReadFile.java:14)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Add the following before creating Scanner class:
System.out.println(new File("test.txt").getAbsolutePath());
It will show you where JVM expects to find the file and whether it is the folder you expect as well.
Also check file permissions. But most likely it is a problem with default JVM directory.
Ahhh you aren't specifying the full file path. When a file path is abbreviated (i.e. test.txt), java assumes that the file is in the same directory as the source code that is running it. So either specify the full path, or move the file.
Move it to the ReadFile directory, i.e. the root of the project
The test.txt file should be in the folder where the file readfile.class exists.
I am aware that this problem has been reported a long time ago, however, I have faced a similar obstacle and then the proposed solutions didn't work, thus I decided to post another answer.
Try using try... catch clause. For instance, only then my code has become compiled by NetBeans.
what worked for me was removing .txt extension from the file name and using . to specify current directory (example shown below).
Scanner scanner = new Scanner(new File("./test"));

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

Categories

Resources