Problem with relative file path - java

So here is my program, which works ok:
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Locale;
public class ScanSum {
public static void main(String[] args) throws IOException {
Scanner s = null;
double sum = 0;
try {
s = new Scanner(new BufferedReader(new FileReader("D:/java-projects/HelloWorld/bin/usnumbers.txt")));
s.useLocale(Locale.US);
while (s.hasNext()) {
if (s.hasNextDouble()) {
sum += s.nextDouble();
} else {
s.next();
}
}
} finally {
s.close();
}
System.out.println(sum);
}
}
As you can see, I am using absolute path to the file I am reading from:
s = new Scanner(new BufferedReader(new FileReader("D:/java-projects/HelloWorld/bin/usnumbers.txt")));
The problem arises when I try to use the relative path:
s = new Scanner(new BufferedReader(new FileReader("usnumbers.txt")));
I get an error:
Exception in thread "main" java.lang.NullPointerException
at ScanSum.main(ScanSum.java:24)
The file usnumbers.txt is in the same directory as the ScanSum.class file:
D:/java-projects/HelloWorld/bin/ScanSum.class
D:/java-projects/HelloWorld/bin/usnumbers.txt
How could I solve this?

If aioobe#'s suggestion doesn't work for you, and you need to find out which directory the app is running from, try logging the following:
new File(".").getAbsolutePath()

From which directory is the class file executed? (That would be the current working directory and base directory for relative paths.)
If you simply launch the application from eclipse, the project directory will be the working directory, and you should in that case use "bin/usnumbers.txt".

The NullPointerException is due to the fact that new FileReader() expression is throwing a FileNotFoundException, and the variable s is never re-assigned a non-null value.
The file "usnumbers.txt" is not found because relative paths are resolved (as with all programs) relative to the current working directory, not one of the many entries on the classpath.
To fix the first problem, never assign a meaningless null value just to hush the compiler warnings about unassigned variables. Use a pattern like this:
FileReader r = new FileReader(path);
try {
Scanner s = new Scanner(new BufferedReader(r));
...
} finally {
r.close();
}
For the second problem, change directories to the directory that contains "usnumbers.txt" before launching java. Or, move that file to the directory from which java is run.

It must be a FileNotFoundException causing NPE in the finally block.
Eclipse, by default, executes the class with the project folder (D:/java-projects/HelloWorld in your case ) as the working directory. Put the usnumbers.txt file in that folder and try. Or change the working directory in Run Configuration -> Argument tab

Since your working directory is “D:/java-projects/HelloWorld”
#pdbartlett's id is great, But
String filePath = new File(".").getAbsolutePath()
will output "D:/java-projects/HelloWorld/." which is not easy to add your extra relative path like "filePath" + "/src/main/resources/" + FILENAME which located in resources folder.
I suggest with String filePath = new File("").getAbsolutePath() which return the project root folder

In Eclipse, you can also look under "Run Configurations->Than TAB "Classpath".
By default the absolut path is listed under "User Entries" in [icon] 'your.path' (default classpath)

Put the file in resources folder.
ClassLoader classLoader = getClass().getClassLoader();
String file1 = classLoader.getResource("myfile.csv").getPath();

Related

Inputting a text file into a program?

I had a lecture today on inputting and outputting but it didn't really seem to explain where the text file is etc..
here is my code:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I get a file not found exception but the text file is in the same folder as the program?
Please first read up on the difference between relative and absolute paths. An absolute path is:
C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\lab1task3.txt
A relative path would be just "lab1task3.txt", which is what is given. That means that lab1task3.txt can be found relative to the working directory (e.g if the working directory was "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" then it would find it).
However, you could also use an absolute path, but remember that doing so means that it will only work if a file is in the same place on the machine running it. E.g, if you submit with "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" in your code then it will only work if someone else has that same file and location on their computer. Please note that if this is an assignment, the module convenor/marker probably does not have afolder called C:\Users\Ceri.... If you submit your work using a relative path, anyone using your code just needs to make sure the file is relatively in the same place (e.g in the same folder).
If this doesn't matter, you need to escape the back slash characters with another back slash in the path. This should work:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I notice you are using eclipse. Your "working directory" is your workspace. Therefore you want to move your file to:
C:\Users\Ceri\workspace1\inputoutput\lab1task3.txt
This should work for you using a "relative" path which you had in your opening post.
You're confusing class file location and the "user's working directory", the latter being what Java uses to determine the root of the file path (unless absolute paths are needed), and you can find its location easily via:
System.out.println(System.getProperty("user.dir"));
I advise you to forgo use of files altogether when all you need to do is read in data, and instead get the text file as a program resource:
// where you swap the name of your class for MyClass
InputStream fileResource = MyClass.class.getResourceAsStream("myFile.txt");
Scanner scanner = new Scanner(inputStream);
Note that if you must use a File, then find out what the user's working directory is, as shown above, and then tailor your file path so that it is relative to this working directory.
Try:
File file = new File("src/inputoutput/lab1task3.txt");
My guess is that your current working directory is not the same place as the project location. If your working directory were, the file would definitely be found if it does indeed have that name.
To workaround this issue you can always be using a InputStream instead, like so:
InputStream inputStream = new InputStream("lab1task3.txt");
Scanner scanner = new Scanner(inputStream);
If you want to see your current working directory you can use something like this:
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}

java FileInputStream cannot find file

I'm very new at coding java and I'm having a lot of difficulty.
I'm suppose to write a program using bufferedreader that reads from a file, that I have already created named "scores.txt".
So I have a method named processFile that is suppose to set up the BufferedReader and loop through the file, reading each score. Then, I need to convert the score to an integer, add them up, and display the calculated mean.
I have no idea how to add them up and calculate the mean, but I'm currently working on reading from the file.
It keeps saying that it can't fine the file, but I know for sure that I have a file in my documents named "scores.txt".
This is what I have so far...it's pretty bad. I'm just not so good at this :( Maybe there's is a different problem?
public static void main(String[] args) throws IOException,
FileNotFoundException {
String file = "scores.txt";
processFile("scores.txt");
//calls method processFile
}
public static void processFile (String file)
throws IOException, FileNotFoundException{
String line;
//lines is declared as a string
BufferedReader inputReader =
new BufferedReader (new InputStreamReader
(new FileInputStream(file)));
while (( line = inputReader.readLine()) != null){
System.out.println(line);
}
inputReader.close();
}
There are two main options available
Use absolute path to file (begins from drive letter in Windows or
slash in *.nix). It is very convenient for "just for test" tasks.
Sample
Windows - D:/someFolder/scores.txt,
*.nix - /someFolder/scores.txt
Put file to project root directory, in such case it will be visible
to class loader.
Place the scores.txt in the root of your project folder, or put the full path to the file in String file.
The program won't know to check your My Documents folder for scores.txt
If you are using IntelliJ, create an input.txt file in your package and right click the input.txt file and click copy path. You can now use that path as an input parameter.
Example:
in = new FileInputStream("C:\\Users\\mda21185\\IdeaProjects\\TutorialsPointJava\\src\\com\\tutorialspoint\\java\\input.txt");
Take the absolute path from the local system if you'r in eclipse then right-click on the file and click on properties you will get the path copy it and put as below this worked for me In maven project keep the properties file in src/main/resources `
private static Properties properties = new Properties();
public Properties simpleload() {
String filepath="C:/Users/shashi_kailash/OneDrive/L3/JAVA/TZA/NewAccount/AccountConnector/AccountConnector-DEfgvf/src/main/resources/sample.properties";
try(FileInputStream fis = new FileInputStream(filepath);) {
//lastModi = propFl.lastModified();
properties.load(fis);
} catch (Exception e) {
System.out.println("Error loading the properties file : sample.properties");
e.printStackTrace();
}
return properties;
}`

System cannot find the file

I am using the Scanner libraries to build a file reader, I have followed the outline in the Libraries and it compiles fine, but when I run it I get a FileNotFoundException : text.txt (The system cannot find the file specified). The file is located in the same folder as the .java file but it still says that it's not there.
Below is the code that I have any help would be great.
import java.util.*;
import java.io.*;
class Conjecture {
public static void main(String[] args) throws IOException {
Scanner scanner = null;
try {
scanner = new Scanner(new BufferedReader(new FileReader("text.txt")));
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
} finally {
if (scanner != null) {
scanner.close();
System.out.println("done");
}
}
}
}
Your file needs to be in the working dir of your runtime JVM. If you are not sure about that, you can do the following :
File file = new File(".");
System.out.println(file.getAbsolutePath());
You need to have the file in the same directory as your .class, not your .java. When compiling from an IDE the .class file usually gets placed in a build directory. Using the absolute path would also work, as Kevin suggested, or adding the file as a resource to a jar file and loading it as resource.
for debug purposes print canonical path of your file:
File file = new new File("text.txt");
System.out.println(file.getCanonicalPath());
so you can see where your file should be located

FileInputStream error Java

I am trying to read a file in Java called "KFormLList.txt". It is saved in the default package along with this program, yet when I try to run it I get this error message: "Error: KFormLList.txt (The system cannot find the file specified)"
What am I doing wrong? Thanks for any help.
import java.io.*;
public class VLOCGenerater {
/**
* #param args
*/
public static void main(String[] args) {
try {
//Read the text file "KFormLList.txt"
FileInputStream fis = new FileInputStream("KFormLList.txt");
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String strLine;
int V = 0;
int LOC = 0;
while((strLine = br.readLine())!= null ){
if (strLine.trim().length() != 0){
System.out.println(strLine);
V++;
}
else {
LOC++;
}
}
System.out.println("V = " + V);
System.out.println("LOC = " + LOC);
dis.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Try putting the text file in the root directory of your project.
The name parameter passed into the FileInputStream constructor is the path name to the file in the file system.
A pathname, whether abstract or in string form, may be either absolute
or relative. An absolute pathname is complete in that no other
information is required in order to locate the file that it denotes. A
relative pathname, in contrast, must be interpreted in terms of
information taken from some other pathname. By default the classes in
the java.io package always resolve relative pathnames against the
current user directory. This directory is named by the system property
user.dir, and is typically the directory in which the Java virtual
machine was invoked.
I assumed you were using Eclipse, by default Eclipse sets the user.dir to your the root of your project. From reading other material, Netbeans follows the same convention.
This can be tested with the following code, which should output the path to your project:
System.out.println(System.getProperty("user.dir"));
Placing the file in the root of your directory allows it to be found by the FileInputStream.
If you're using NetBeans (perhaps similar for Eclipse), make sure that your file is in NetbeansProjects/YourProject/
If you have compiled your program to .jar file, put the txt to same place where .jar is.
Either you put the file in the "root directory" of your project or provide the "absolute path" of the file as argument to FileInputStream.
Hope that helps. :).
This way, the program expects the file in the working folder,. i.e. where you execute java. For loading from classpath (Default package), try getResourceAsStream.

When I try to read a file with Java using Eclipse, it always says it can't find it?

I've created this simple program in Eclipse:
import java.util.*;
import java.io.*;
public class prob1 {
public static void main(String[] args)
{
try
{
FileReader in = new FileReader("practice.in");
Scanner scanner = new Scanner(in);
while(scanner.hasNext())
{
int number = scanner.nextInt();
if(number==0)break;
int sum = 0;
for (int i=0; i<number; i++)
{
int x = scanner.nextInt();
sum += x;
}
System.out.println("Sum = "+sum);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I also have a "practice.in" file in the same folder as this practice.java file is (the src folder in Eclipse."
However, when I try to run it, it can never find it. What is eclipse doing with the paths that I can simply do FileReader("practice.in") when practice.in is in the same directory as the java file? Does this have something to do with my workings directory?
The default folder in eclipse is the project root, not the src folder. You need to move the file or specify the relative path of "src/practice.in"
If practice.in levels at the same directory level as your java file, then you can also use [Class.getResourceAsStream()](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)):
InputStream steam = prob1.class.getResourceAsStream("practice.in");
Scanner scanner = new Scanner(stream);
...
This would work regardless of where you invoked the java file.
Java would access the file relative to the directory from which the java command is being run, which is your project root directory. So you would have to give the full path to that file, starting at the project root.
Additionally, if you're the Spring library, you can use the application context to find a file with a given name anywhere in the classpath.

Categories

Resources