currently I'm working on a project and I have to change the savepath of my application. So I will firstly check if the directory exists using
File file = new File(path);
file.exists();
My problem is that the method file.exists() returns false even when I try to input C: as my path. Nevertheless, if I don't specify any folder, let say :
File file = new File("testFile.xml");
Then the new file will be created in the main directory. I suspect Eclipse automatically adds a relative path everytime I do the check since when I use text editor, the following returns true
new File("C:").exists()
Now, is there any way to tell Eclipse to recognise the path that I enter as an absolute path?
Thanks!
EDITED ****
I found that my problem is that Eclipse seems to auto append every file path that I create with the source directory
File = new File("C:/")
will give me
"C:\Users\Christopher\Documents\School Stuff\CS2103\JOBS\main\C:\"
which is automatically appended by eclipse with the project directory and hence, disabling me from creating file outside of my project directory
Could you try file.getAbsoluteFile().exists() ?
File.isAbsolute():
File file = new File(path);
if (file.isAbsolute()) {
}
in Eclipse, right click on project and go to run> run configuration and go to arguments give the default path for saving file.... project always create file on that location.
File fileTest = new File("C:/test");
if (!fileTest.exists()) {
if (fileTest.mkdirs()) {
fileTest.setReadable(true, false);
fileTest.setWritable(true, false);
} else {
System.out.println("Failed To Create Directories! :-"+ "C:/");
}
}
Related
I have an XML file in a folder within my Java project, and I'd like to get its absolute path, so I can load it as a File in order to parse it(DOM). Instead of using an absolute/relative path, I want to specify only the file name, and get the absolute path after that. I tried to do this in a few different ways, but there is always a folder name missing from the path I get.
I get:
C:\Users\user\workspace\projectName\Input.xml<br>
instead of:
C:\Users\user\workspace\projectName\\**Folder1**\\Input.xml
-
File input = new File(project.getFile("Input.xml").getLocation().toString());`
File input = new File(project.getFile("Input.xml").getRawLocation().makeAbsolute().toString());
File input = new File(project.getFile("Input.xml").getLocationURI().getRawPath().toString());
File input = new File(project.getFile("Input.xml").getFullPath().toFile().getAbsolutePath());
How can I get the correct path, that includes that Folder1?
Reading your question (your project are in workspace directory) I suppose you're talking of a project in Eclipse.
Well the default directory where your app run into Eclipse is right the base dir of your project.
So if you run something like this in your main:
Files.newDirectoryStream(Paths.get("."))
.forEach(path -> {
System.out.println(path);
System.out.println(path.toFile().getAbsolutePath());
});
You should see all the files and directory that are in your project.
So if what you want is just the absolute path to your project run:
System.out.println(Paths.get(".").toFile().getAbsolutePath());
If you want open the resource Input.xml specifying only the name, I suggest to move all the files you need in a directory and run a method like this:
public static File getFileByName(String name, String path) throws IOException {
ArrayList<File> files = new ArrayList<>();
Files.newDirectoryStream(Paths.get(path))
.forEach(p -> {
if (p.getFileName()
.equals(name))
files.add(p.toFile());
});
return files.size() > 0 ? files.get(0) : null;
}
So with the code below it creates the file in the folder
File f = new File(path);
if(!f.exists())
f.mkdirs();
, but i only want to create the directory, because after this i use this code
file.transferTo(new File(path));
which saves a Multipart file to the same location, but it throws and error because there is already a file. Is there a way only to create the folder without the file ? One solution is to delete the first file, but looking for better solution
EDIT:
File f = new File(path);
this line creates the folders and the file, it shouldn't. I use java 8 and IntelliJ 14
SOLUTION:
The problem was Intellij or Intellij debug watches. After restarting it and clearing watches which were like:
new File(path)
file.transferTo(new File(path))
f.exists()
The code started working.
It should be
f.getParentFile().mkdirs();
You don't need to check for existence beforehand: mkdirs() already does that.
File dir = new File("<Your_Path>/TestDirectory");
// attempt to create the directory here
boolean successful = dir.mkdir();
if (successful)
{
// creating the directory succeeded
System.out.println("directory was created successfully");
}
else
{
// creating the directory failed
System.out.println("failed trying to create the directory");
}
You can create your files inside your directory path from then on....
I want to search for files in a directory. Therefore I want to get the directory in a File object but i'm getting a file instead of a directory. This is what I'm doing, it prints false but I want it to be true.
URL url = getClass().getResource("/strategy/viewconfigurations/");
File folder = new File(url.toString());
System.out.println(folder.isDirectory());
How can I load this way a directory?
It seems path or String you will got from the URL object cause problem.
You passed file path which you will got from the url.toString().
You need to change below line
File folder = new File(url.toString());
with this line
File folder = new File(url.getPath());
You need path of that folder which will you get from URL.getPath() function.
I hope this is what you need.
If you need an alternative for Java 7+ to Yagnesh Agola's post for finding a directory from a classpath folder, you could you also the newer java.nio.file.Path class.
Here is an example:
URL outputXml = Thread.currentThread().getContextClassLoader().getResource("outputXml");
if(outputXml == null) {
throw new RuntimeException("Cannot find path in classpath");
}
Path path = Paths.get(outputXml.toURI());
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
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