File not found in same folder Java - java

I am trying to read a file in Java. I wrote a program and saved the file in the exact same folder as my program. Yet, I keep getting a FileNotFoundException. Here is the code:
public static void main(String[] args) throws IOException {
Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
File f = new File("file.txt");
ArrayList<String> al = readFile(f, ht);
}
public static ArrayList<String> readFile(File f, Hashtable<String, Integer> ht) throws IOException{
ArrayList<String> al = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
int ctr = 0;
}
...
return al;
}
Here is the stack trace:
Exception in thread "main" java.io.FileNotFoundException: file.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at csfhomework3.ScramAssembler.readFile(ScramAssembler.java:26)
at csfhomework3.ScramAssembler.main(ScramAssembler.java:17)
I don't understand how the file can't be found if it's in the exact same folder as the program. I'm running the program in eclipse and I checked my run configurations for any stray arguments and there are none. Does anyone see what's wrong?

Because the File isn't where you think it is. Print the path that your program is attempting to read.
File f = new File("file.txt");
try {
System.out.println(f.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
Per the File.getCanonicalPath() javadoc, A canonical pathname is both absolute and unique. The precise definition of canonical form is system-dependent.

Check the Eclipse run configuration. Look on the second tab "Arguments", at the bottom pane where it says "Working Directory". That's the place where the program gets launched and where it will expect to find the file. Usually in Eclipse it launches your program with the current working directory set to be the base project directory. If you have the java class file in a source folder and are using proper package (e.g., "com.mycompany.package"), then the data file will be in a directory like "src/com/mycompany/package" which is quite a different directory from the project directory.
HTH

File needs to be in the class path and not in the source path. Copy the file in output/class files folder and it should be available.

You should probably check out this question: Java can't find file when running through Eclipse
Basically you need to be sure where the execution is taking place (current directory) and how your SO will resolve the relative paths. Try changing the working directory in Eclipse' Run Configurations>Arguments or provide the absolute filename

I'm extremely late to responding to this question, but I see that this is still an extremely hot topic to this day. It may not seem obvious, but what you want to use here is actually the newer file-handling i/o library, java.nio. The below explained example shows how to read a String from a file path, but I encourage you to take a look at the docs if you have a different use.
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Files;
public static void main(String[] args) throws IOException {
Path path = Path.of("app/src/main/java/pkgname/file.txt");
String content = Files.readString(path);
System.out.println(content); // Prints file content
}
Okay, code done, now time for the explanation. I'll start off with the import statements. java.io.IOException is necessary for some exception-handling. (Sidenote: Do not omit the throws IOException and/or the IOException import. Otherwise Files.readString() may throw an error in your editor, which I'll get to shortly). The Path class import is necessary to actually get the file, and the Files class import is necessary for file operations.
Now, the main function itself. The first line receives a Path object representing a file for you to actually read/write. Here the question of path name arises, which is the basis of the question. I have seen other solutions that tell you to take the absolute path of your file, but don't do that! It's extremely bad practice, especially with open-source or public code. Path.of actually allows you to use the path relative to your root folder (unless it isn't in a directory, simply inputting the file name does not work, I'm afraid). The example path name I gave is an example of a Gradle project. Next line, we get the content of the file as a String using a method from Files. Again, if you have a different use for a file, you can check the docs (a different method from the Files class will probably work for you). On the final line, we print the result. Hooray! Our output is just what we needed.
There you have it, using Path instead of File is the solution to this annoying bug. Hopefully this helps!

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.

Modify the feet to meters program to read from, write to a file. The input file named “feet.txt” and the output file “meters.txt” [duplicate]

I have an assignment for my CS class where it says to read a file with several test scores and asks me to sum and average them. While summing and averaging is easy, I am having problems with the file reading. The instructor said to use this syntax
Scanner scores = new Scanner(new File("scores.dat"));
However, this throws a FileNotFoundException, but I have checked over and over again to see if the file exists in the current folder, and after that, I figured that it had to do something with the permissions. I changed the permissions for read and write for everyone, but it still did not work and it still keeps throwing the error. Does anyone have any idea why this may be occurring?
EDIT: It was actually pointing to a directory up, however, I have fixed that problem. Now file.exists() returns true, but when I try to put it in the Scanner, it throws the FileNotFoundException
Here is all my code
import java.util.Scanner;
import java.io.*;
public class readInt{
public static void main(String args[]){
File file = new File("lines.txt");
System.out.println(file.exists());
Scanner scan = new Scanner(file);
}
}
There are a number situation where a FileNotFoundException may be thrown at runtime.
The named file does not exist. This could be for a number of reasons including:
The pathname is simply wrong
The pathname looks correct but is actually wrong because it contains non-printing characters (or homoglyphs) that you did not notice
The pathname is relative, and it doesn't resolve correctly relative to the actual current directory of the running application. This typically happens because the application's current directory is not what you are expecting or assuming.
The path to the file is is broken; e.g. a directory name of the path is incorrect, a symbolic link on the path is broken, or there is a permission problem with one of the path components.
The named file is actually a directory.
The named file cannot be opened for reading for some reason.
The good news that, the problem will inevitably be one of the above. It is just a matter of working out which. Here are some things that you can try:
Calling file.exists() will tell you if any file system object exists with the given name / pathname.
Calling file.isDirectory() will test if it is a directory.
Calling file.canRead() will test if it is a readable file.
This line will tell you what the current directory is:
System.out.println(new File(".").getAbsolutePath());
This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trailing whitespace:
System.out.println("The path is '" + path + "'");
Look for unexpected spaces, line breaks, etc in the output.
It turns out that your example code has a compilation error.
I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - unreported exception java.io.FileNotFoundException; must
be caught or declared to be thrown
If you change your code to the following, it will fix that problem.
public static void main(String[] args) throws FileNotFoundException {
File file = new File("scores.dat");
System.out.println(file.exists());
Scanner scan = new Scanner(file);
}
Explanation: the Scanner(File) constructor is declared as throwing the FileNotFoundException exception. (It happens the scanner it cannot open the file.) Now FileNotFoundException is a checked exception. That means that a method in which the exception may be thrown must either catch the exception or declare it in the throws clause. The above fix takes the latter approach.
The code itself is working correctly. The problem is, that the program working path is pointing to other place than you think.
Use this line and see where the path is:
System.out.println(new File(".").getAbsoluteFile());
Obviously there are a number of possible causes and the previous answers document them well, but here's how I solved this for in one particular case:
A student of mine had this problem and I nearly tore my hair out trying to figure it out. It turned out that the file didn't exist, even though it looked like it did. The problem was that Windows 7 was configured to "Hide file extensions for known file types." This means that if file appears to have the name "data.txt" its actual filename is "data.txt.txt".
Hope this helps others save themselves some hair.
I recently found interesting case that produces FileNotFoundExeption when file is obviously exists on the disk.
In my program I read file path from another text file and create File object:
//String path was read from file
System.out.println(path); //file with exactly same visible path exists on disk
File file = new File(path);
System.out.println(file.exists()); //false
System.out.println(file.canRead()); //false
FileInputStream fis = new FileInputStream(file); // FileNotFoundExeption
The cause of the problem was that the path contained invisible \r\n characters at the end.
The fix in my case was:
File file = new File(path.trim());
To generalize a bit, the invisible / non-printing characters could have include space or tab characters, and possibly others, and they could have appeared at the beginning of the path, at the end, or embedded in the path. Trim will work in some cases but not all. There are a couple of things that you can help to spot this kind of problem:
Output the pathname with quote characters around it; e.g.
System.out.println("Check me! '" + path + "'");
and carefully check the output for spaces and line breaks where they shouldn't be.
Use a Java debugger to carefully examine the pathname string, character by character, looking for characters that shouldn't be there. (Also check for homoglyph characters!)
An easy fix, which worked for me, is moving my files out of src and into the main folder of the project. It's not the best solution, but depending on the magnitude of the project and your time, it might be just perfect.
Reading and writing from and to a file can be blocked by your OS depending on the file's permission attributes.
If you are trying to read from the file, then I recommend using File's setReadable method to set it to true, or, this code for instance:
String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file;
File f = new File(arbitrary_path);
f.setReadable(true);
data_of_file = Files.readAllBytes(f);
f.setReadable(false); // do this if you want to prevent un-knowledgeable
//programmers from accessing your file.
If you are trying to write to the file, then I recommend using File's setWritable method to set it to true, or, this code for instance:
String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file = { (byte) 0x00, (byte) 0xFF, (byte) 0xEE };
File f = new File(arbitrary_path);
f.setWritable(true);
Files.write(f, byte_array);
f.setWritable(false); // do this if you want to prevent un-knowledgeable
//programmers from changing your file (for security.)
Apart from all the other answers mentioned here, you can do one thing which worked for me.
If you are reading the path through Scanner or through command line args, instead of copy pasting the path directly from Windows Explorer just manually type in the path.
It worked for me, hope it helps someone :)
I had this same error and solved it simply by adding the src directory that is found in Java project structure.
String path = System.getProperty("user.dir") + "\\src\\package_name\\file_name";
File file = new File(path);
Scanner scanner = new Scanner(file);
Notice that System.getProperty("user.dir") and new File(".").getAbsolutePath() return your project root directory path, so you have to add the path to your subdirectories and packages
You'd obviously figure it out after a while but just posting this so that it might help someone. This could also happen when your file path contains any whitespace appended or prepended to it.
Use single forward slash and always type the path manually. For example:
FileInputStream fi= new FileInputStream("D:/excelfiles/myxcel.xlsx");
What worked for me was catching the exception. Without it the compiler complains even if the file exists.
InputStream file = new FileInputStream("filename");
changed to
try{
InputStream file = new FileInputStream("filename");
System.out.println(file.available());
}
catch (Exception e){
System.out.println(e);
}
This works for me. It also can read files such txt, csv and .in
public class NewReader {
public void read() throws FileNotFoundException, URISyntaxException {
File file = new File(Objects.requireNonNull(NewReader.class.getResource("/test.txt")).toURI());
Scanner sc = new Scanner(file);
while (sc.hasNext()) {
String text = sc.next();
System.out.println(text);
}
}
}
the file is located in resource folder generated by maven. If you have other folders nested in, just add it to the file name like "examples/test.txt".

Output of Reading the file is not getting as Expected? [duplicate]

I have an assignment for my CS class where it says to read a file with several test scores and asks me to sum and average them. While summing and averaging is easy, I am having problems with the file reading. The instructor said to use this syntax
Scanner scores = new Scanner(new File("scores.dat"));
However, this throws a FileNotFoundException, but I have checked over and over again to see if the file exists in the current folder, and after that, I figured that it had to do something with the permissions. I changed the permissions for read and write for everyone, but it still did not work and it still keeps throwing the error. Does anyone have any idea why this may be occurring?
EDIT: It was actually pointing to a directory up, however, I have fixed that problem. Now file.exists() returns true, but when I try to put it in the Scanner, it throws the FileNotFoundException
Here is all my code
import java.util.Scanner;
import java.io.*;
public class readInt{
public static void main(String args[]){
File file = new File("lines.txt");
System.out.println(file.exists());
Scanner scan = new Scanner(file);
}
}
There are a number situation where a FileNotFoundException may be thrown at runtime.
The named file does not exist. This could be for a number of reasons including:
The pathname is simply wrong
The pathname looks correct but is actually wrong because it contains non-printing characters (or homoglyphs) that you did not notice
The pathname is relative, and it doesn't resolve correctly relative to the actual current directory of the running application. This typically happens because the application's current directory is not what you are expecting or assuming.
The path to the file is is broken; e.g. a directory name of the path is incorrect, a symbolic link on the path is broken, or there is a permission problem with one of the path components.
The named file is actually a directory.
The named file cannot be opened for reading for some reason.
The good news that, the problem will inevitably be one of the above. It is just a matter of working out which. Here are some things that you can try:
Calling file.exists() will tell you if any file system object exists with the given name / pathname.
Calling file.isDirectory() will test if it is a directory.
Calling file.canRead() will test if it is a readable file.
This line will tell you what the current directory is:
System.out.println(new File(".").getAbsolutePath());
This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trailing whitespace:
System.out.println("The path is '" + path + "'");
Look for unexpected spaces, line breaks, etc in the output.
It turns out that your example code has a compilation error.
I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - unreported exception java.io.FileNotFoundException; must
be caught or declared to be thrown
If you change your code to the following, it will fix that problem.
public static void main(String[] args) throws FileNotFoundException {
File file = new File("scores.dat");
System.out.println(file.exists());
Scanner scan = new Scanner(file);
}
Explanation: the Scanner(File) constructor is declared as throwing the FileNotFoundException exception. (It happens the scanner it cannot open the file.) Now FileNotFoundException is a checked exception. That means that a method in which the exception may be thrown must either catch the exception or declare it in the throws clause. The above fix takes the latter approach.
The code itself is working correctly. The problem is, that the program working path is pointing to other place than you think.
Use this line and see where the path is:
System.out.println(new File(".").getAbsoluteFile());
Obviously there are a number of possible causes and the previous answers document them well, but here's how I solved this for in one particular case:
A student of mine had this problem and I nearly tore my hair out trying to figure it out. It turned out that the file didn't exist, even though it looked like it did. The problem was that Windows 7 was configured to "Hide file extensions for known file types." This means that if file appears to have the name "data.txt" its actual filename is "data.txt.txt".
Hope this helps others save themselves some hair.
I recently found interesting case that produces FileNotFoundExeption when file is obviously exists on the disk.
In my program I read file path from another text file and create File object:
//String path was read from file
System.out.println(path); //file with exactly same visible path exists on disk
File file = new File(path);
System.out.println(file.exists()); //false
System.out.println(file.canRead()); //false
FileInputStream fis = new FileInputStream(file); // FileNotFoundExeption
The cause of the problem was that the path contained invisible \r\n characters at the end.
The fix in my case was:
File file = new File(path.trim());
To generalize a bit, the invisible / non-printing characters could have include space or tab characters, and possibly others, and they could have appeared at the beginning of the path, at the end, or embedded in the path. Trim will work in some cases but not all. There are a couple of things that you can help to spot this kind of problem:
Output the pathname with quote characters around it; e.g.
System.out.println("Check me! '" + path + "'");
and carefully check the output for spaces and line breaks where they shouldn't be.
Use a Java debugger to carefully examine the pathname string, character by character, looking for characters that shouldn't be there. (Also check for homoglyph characters!)
An easy fix, which worked for me, is moving my files out of src and into the main folder of the project. It's not the best solution, but depending on the magnitude of the project and your time, it might be just perfect.
Reading and writing from and to a file can be blocked by your OS depending on the file's permission attributes.
If you are trying to read from the file, then I recommend using File's setReadable method to set it to true, or, this code for instance:
String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file;
File f = new File(arbitrary_path);
f.setReadable(true);
data_of_file = Files.readAllBytes(f);
f.setReadable(false); // do this if you want to prevent un-knowledgeable
//programmers from accessing your file.
If you are trying to write to the file, then I recommend using File's setWritable method to set it to true, or, this code for instance:
String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file = { (byte) 0x00, (byte) 0xFF, (byte) 0xEE };
File f = new File(arbitrary_path);
f.setWritable(true);
Files.write(f, byte_array);
f.setWritable(false); // do this if you want to prevent un-knowledgeable
//programmers from changing your file (for security.)
Apart from all the other answers mentioned here, you can do one thing which worked for me.
If you are reading the path through Scanner or through command line args, instead of copy pasting the path directly from Windows Explorer just manually type in the path.
It worked for me, hope it helps someone :)
I had this same error and solved it simply by adding the src directory that is found in Java project structure.
String path = System.getProperty("user.dir") + "\\src\\package_name\\file_name";
File file = new File(path);
Scanner scanner = new Scanner(file);
Notice that System.getProperty("user.dir") and new File(".").getAbsolutePath() return your project root directory path, so you have to add the path to your subdirectories and packages
You'd obviously figure it out after a while but just posting this so that it might help someone. This could also happen when your file path contains any whitespace appended or prepended to it.
Use single forward slash and always type the path manually. For example:
FileInputStream fi= new FileInputStream("D:/excelfiles/myxcel.xlsx");
What worked for me was catching the exception. Without it the compiler complains even if the file exists.
InputStream file = new FileInputStream("filename");
changed to
try{
InputStream file = new FileInputStream("filename");
System.out.println(file.available());
}
catch (Exception e){
System.out.println(e);
}
This works for me. It also can read files such txt, csv and .in
public class NewReader {
public void read() throws FileNotFoundException, URISyntaxException {
File file = new File(Objects.requireNonNull(NewReader.class.getResource("/test.txt")).toURI());
Scanner sc = new Scanner(file);
while (sc.hasNext()) {
String text = sc.next();
System.out.println(text);
}
}
}
the file is located in resource folder generated by maven. If you have other folders nested in, just add it to the file name like "examples/test.txt".

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

Changing the current working directory in Java?

How can I change the current working directory from within a Java program? Everything I've been able to find about the issue claims that you simply can't do it, but I can't believe that that's really the case.
I have a piece of code that opens a file using a hard-coded relative file path from the directory it's normally started in, and I just want to be able to use that code from within a different Java program without having to start it from within a particular directory. It seems like you should just be able to call System.setProperty( "user.dir", "/path/to/dir" ), but as far as I can figure out, calling that line just silently fails and does nothing.
I would understand if Java didn't allow you to do this, if it weren't for the fact that it allows you to get the current working directory, and even allows you to open files using relative file paths....
There is no reliable way to do this in pure Java. Setting the user.dir property via System.setProperty() or java -Duser.dir=... does seem to affect subsequent creations of Files, but not e.g. FileOutputStreams.
The File(String parent, String child) constructor can help if you build up your directory path separately from your file path, allowing easier swapping.
An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.
The relevant OpenJDK bug was closed in 2008 as "will not fix".
If you run your legacy program with ProcessBuilder, you will be able to specify its working directory.
There is a way to do this using the system property "user.dir". The key part to understand is that getAbsoluteFile() must be called (as shown below) or else relative paths will be resolved against the default "user.dir" value.
import java.io.*;
public class FileUtils
{
public static boolean setCurrentDirectory(String directory_name)
{
boolean result = false; // Boolean indicating whether directory was set
File directory; // Desired current working directory
directory = new File(directory_name).getAbsoluteFile();
if (directory.exists() || directory.mkdirs())
{
result = (System.setProperty("user.dir", directory.getAbsolutePath()) != null);
}
return result;
}
public static PrintWriter openOutputFile(String file_name)
{
PrintWriter output = null; // File to open for writing
try
{
output = new PrintWriter(new File(file_name).getAbsoluteFile());
}
catch (Exception exception) {}
return output;
}
public static void main(String[] args) throws Exception
{
FileUtils.openOutputFile("DefaultDirectoryFile.txt");
FileUtils.setCurrentDirectory("NewCurrentDirectory");
FileUtils.openOutputFile("CurrentDirectoryFile.txt");
}
}
It is possible to change the PWD, using JNA/JNI to make calls to libc. The JRuby guys have a handy java library for making POSIX calls called jnr-posix. Here's the maven info
As mentioned you can't change the CWD of the JVM but if you were to launch another process using Runtime.exec() you can use the overloaded method that lets you specify the working directory. This is not really for running your Java program in another directory but for many cases when one needs to launch another program like a Perl script for example, you can specify the working directory of that script while leaving the working dir of the JVM unchanged.
See Runtime.exec javadocs
Specifically,
public Process exec(String[] cmdarray,String[] envp, File dir) throws IOException
where dir is the working directory to run the subprocess in
If I understand correctly, a Java program starts with a copy of the current environment variables. Any changes via System.setProperty(String, String) are modifying the copy, not the original environment variables. Not that this provides a thorough reason as to why Sun chose this behavior, but perhaps it sheds a little light...
The working directory is a operating system feature (set when the process starts).
Why don't you just pass your own System property (-Dsomeprop=/my/path) and use that in your code as the parent of your File:
File f = new File ( System.getProperty("someprop"), myFilename)
The smarter/easier thing to do here is to just change your code so that instead of opening the file assuming that it exists in the current working directory (I assume you are doing something like new File("blah.txt"), just build the path to the file yourself.
Let the user pass in the base directory, read it from a config file, fall back to user.dir if the other properties can't be found, etc. But it's a whole lot easier to improve the logic in your program than it is to change how environment variables work.
I have tried to invoke
String oldDir = System.setProperty("user.dir", currdir.getAbsolutePath());
It seems to work. But
File myFile = new File("localpath.ext");
InputStream openit = new FileInputStream(myFile);
throws a FileNotFoundException though
myFile.getAbsolutePath()
shows the correct path.
I have read this. I think the problem is:
Java knows the current directory with the new setting.
But the file handling is done by the operation system. It does not know the new set current directory, unfortunately.
The solution may be:
File myFile = new File(System.getPropety("user.dir"), "localpath.ext");
It creates a file Object as absolute one with the current directory which is known by the JVM. But that code should be existing in a used class, it needs changing of reused codes.
~~~~JcHartmut
You can use
new File("relative/path").getAbsoluteFile()
after
System.setProperty("user.dir", "/some/directory")
System.setProperty("user.dir", "C:/OtherProject");
File file = new File("data/data.csv").getAbsoluteFile();
System.out.println(file.getPath());
Will print
C:\OtherProject\data\data.csv
You can change the process's actual working directory using JNI or JNA.
With JNI, you can use native functions to set the directory. The POSIX method is chdir(). On Windows, you can use SetCurrentDirectory().
With JNA, you can wrap the native functions in Java binders.
For Windows:
private static interface MyKernel32 extends Library {
public MyKernel32 INSTANCE = (MyKernel32) Native.loadLibrary("Kernel32", MyKernel32.class);
/** BOOL SetCurrentDirectory( LPCTSTR lpPathName ); */
int SetCurrentDirectoryW(char[] pathName);
}
For POSIX systems:
private interface MyCLibrary extends Library {
MyCLibrary INSTANCE = (MyCLibrary) Native.loadLibrary("c", MyCLibrary.class);
/** int chdir(const char *path); */
int chdir( String path );
}
The other possible answer to this question may depend on the reason you are opening the file. Is this a property file or a file that has some configuration related to your application?
If this is the case you may consider trying to load the file through the classpath loader, this way you can load any file Java has access to.
If you run your commands in a shell you can write something like "java -cp" and add any directories you want separated by ":" if java doesnt find something in one directory it will go try and find them in the other directories, that is what I do.
Use FileSystemView
private FileSystemView fileSystemView;
fileSystemView = FileSystemView.getFileSystemView();
currentDirectory = new File(".");
//listing currentDirectory
File[] filesAndDirs = fileSystemView.getFiles(currentDirectory, false);
fileList = new ArrayList<File>();
dirList = new ArrayList<File>();
for (File file : filesAndDirs) {
if (file.isDirectory())
dirList.add(file);
else
fileList.add(file);
}
Collections.sort(dirList);
if (!fileSystemView.isFileSystemRoot(currentDirectory))
dirList.add(0, new File(".."));
Collections.sort(fileList);
//change
currentDirectory = fileSystemView.getParentDirectory(currentDirectory);

Categories

Resources