Why isn't java finding my file - java

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.

Related

No such file or directory in Intellij while working with filereader

I'm new to IntelliJ. I'm running into problems on running very basic File I/O programs.
import java.io.*;
import java.util.Scanner;
public class NamePlaces {
public static void main(String[] args) throws FileNotFoundException{
String nameTxt = args[0];
String placeTxt = args[1];
Scanner nameScanner = null;
Scanner placeScanner = null;
try{
FileReader names = new FileReader(nameTxt);
FileReader places = new FileReader(placeTxt);
nameScanner = new Scanner(new BufferedReader(names));
placeScanner = new Scanner(new BufferedReader(places));
while(nameScanner.hasNext() && placeScanner.hasNext()){
System.out.format("%s lives in %s \n",nameScanner.next(),placeScanner.next());
}
}finally {
if (nameScanner != null){
nameScanner.close();
}
if (placeScanner != null){
placeScanner.close();
}
}
}
here's my project structure
and here's my output
/usr/lib64/jvm/java/bin/java -javaagent:/home/abhishek/intellij/lib/idea_rt.jar=42185:/home/abhishek/intellij/bin -Dfile.encoding=UTF-8 -classpath /home/abhishek/Documents/code/ideaprojects/files/out/production/files NamePlaces names.txt places.txt
Exception in thread "main" java.io.FileNotFoundException: names.txt (No such file or directory)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112)
at java.base/java.io.FileReader.<init>(FileReader.java:60)
at NamePlaces.main(NamePlaces.java:12)
Process finished with exit code 1
So I've been wrestling with this problem for quite some time now. I do not understand why it won't read the file names.txt when it is available in the src folder as well as the out/production/files folder too. What am I missing. I've tried changing directories, classpath seems right too. I'm out of options here. Any help is appreciated. thanks.
In Java if you are not using class.getResource() it will be looking in the project/surrounding folder. If you compiled the .class file by hand it would work in its current state. But to fix the issue moving names.txt and places.txt to the files project folder will fix it.
I am able to run the program. I however could not figure out a simpler way than this.
So I changed my code by adding
import java.nio.file.Path;
import java.nio.file.Paths;
to the imports.
And inside the main(), I added the following statement to get the path.
Path path = Paths.get('path/to/directory/');
And then I used this path to hard code the path into the call to the FileReader such as
FileReader names = new FileReader(path.toString()+"/"+namesTxt);
This got the program running. I know this is not the optimum or the desired solution but at the moment, I wanted the program to run.
I will update the answer once I learn more about how the IntelliJ works in identifying files because hard coding paths is not a good software design practice.

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

Cannot Read File in Working Directory

I am learning basic I/O for java, and the following example is from Oracle's tutorial. The program flows a FileNotFound exception. I place the file under the working directory, and I also tried to use absolute file path, and the result is still the same. I use Eclipse to write the code. What could be causing this exception? Thanks
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
There are a lot of things that can cause that exception. Here are a few things to try:
-Verify that Xanadu.txt is a file using the isFile() method. If it returns false then you know where your problem is.
-Try placing the file in the project directory.
-Given that you already tried using the absolute file path I would also make sure that your program has permission to look at and write to the file. To check if eclipse has permission go to the properties of your file
Place the file xanadu.txt in the project directory and FileNotFoundException will go away.
FileInputStream will expect an existing input file.
The code probably isn't being executed from the path you expected.
You should use the home folder for this. C:\Users\<User Name> on windows and /home/<User Name> on linux. You can create a folder there to put your files.
To get the home directory, you can use this.
System.getProperty("user.dir")
Other solution would be to pack the files inside the JAR.
If you want to debug your problem, you can get the current directory like this.
<Your Class>.class.getProtectionDomain().getCodeSource().getLocation()

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.

Using Java unable to save to text file

I'm trying to get my submit button to save the GUI in a text file, I've made the GUI and the button listener ...etc but I'm having trouble making the method that saves the information from the GUI into a text file.
so far i have:
public void save() {
File k1 = new File("documents/"+"newfile.txt");
try {
k1.createNewFile();
FileWriter kwriter = new FileWriter(k1);
BufferedWriter bwriter = new BufferedWriter(kwriter);
bwriter.write(txtField1.getText().trim());
bwriter.newLine();
bwriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
but it doesn't seem to work, nothing happens; is there anything I'm missing?
You're file is called .txt - perhaps insert a name in the first row:
File k1 = new File("documents/filename.txt");
You should be getting an error when running that code.
The problem is that the document directory doesn't exist or it is not where you expected.
You can check for the parent directory with:
if(!k1.getParentFile().exists()){
k1.getParentFile().mkdirs();
}
Alternatively you need to set the file to be a more precise location.
org.apache.commons.lang.SystemUtils might be able to help you out here with user home.
i was just think is there a easier way, for example i already have the Jfilechoser open a "save as box" when the "submit" button is pressed so is there a easier way to create the file (saving the gui infomation in a txt file) ?
This is a continuation on your previous question. You should just get the selected file and write to it with help of any Writer, like PrintWriter.
File file = fileChooser.getSelectedFile();
PrintWriter writer = new PrintWriter(file);
try {
writer.println(txtField1.getText().trim());
writer.flush();
} finally {
writer.close();
}
Don't overcomplicate by creating a new File() on a different location and calling File#createFile(). Just writing to it is sufficient.
See also:
Java IO tutorial
update here's an SSCCE, you can just copy'n'paste'n'compile'n'run it.
package com.example;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JFileChooser;
public class Test {
public static void main(String[] args) throws IOException {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
PrintWriter writer = new PrintWriter(file);
try {
writer.println("Hello");
writer.flush();
} finally {
writer.close();
}
Desktop.getDesktop().open(file);
}
}
}
My guess is that the file is being created, but not in the directory that you expect. Check the value of the user.dir system property and see what it shows. This is the current working directory of your JVM.
You may need to either:
Specify a full path in the code (as Martin suggested), e.g. new File("/home/foo/newfile.txt")
Change the working directory of the JVM. The way that you do this depends on how you are launching it (e.g. if you are running the java command directly from a CLI, then just switch directories first, if you are running from an IDE then change the launch configuration, etc.).
As far as I know, you cannot change the working directory at runtime (see this SO question).
Your code is working for me with minor change.
As a debugging process, I would completely delete the directory path and try to use a file only..
instead of
File k1 = new File("documents/"+"newfile.txt");
use
File k1 = new File("newfile.txt");
Check where your file is generated and then create directory there..
Good luck!!

Categories

Resources