I am using Java files in one of my application.
File file = new File("c:\\users\\......");
System.out.println(file.isDirectory());
I don't have a directory or file in the name of "......" in my users directory, but still file.isDirectory returns true, why?
Why does this happen? And how can I avoid this?
Related
I have created a java program that other testers will use to help with their testing. I will be sending them a zip file with the .jar, a readme.txt, and main.properties.txt file.
The main.properties.txt file is a template for the testers to input their DB access credentials. They will update the main.properties file with their db cred's and then attempt to run the .jar from the terminal or command line. The issue I am running into is this. My program needs this updated main.properties.txt file so it can create the connections to our DB's.
What instructions do I need to give in my readme so my program can successfully find the main.properties.txt? Does the main.properties need to be in the same directory as the .jar? Can the testers just create a file on their desktop or documents folders to put the .jar and main.props?
The other question I have is how do I pass this file to my program once its ran from the terminal? Currently it is really easy, because the main.props is part of my program and I can just do something like
Properties prop = new Properties();
FileInputStream in = new FileInputStream("src/main/resources/main.properties");
prop.load(in);
in.close();
But now main.properties is not part of the project anymore. I don't know how to change the code above so that it can find the text from a directory on the local. The location in which they wish to put their main.properties is out of my control so writing a static path will not work. Please help!
There are many ways, I'll show you two.
You need a File object that points to the main.properties file. Then you create a stream on this object new FileInputStream(File) , as you already did by using a String.
The problem of course is to get a relative path to main.properties.txt which works on all systems, regardless where the jar-File is located.
1. Desktop
In this case the main.properties.txt is located at the users desktop. Here is how you access it:
File desktop = new File(System.getProperty("user.home"), "Desktop");
File target = new File(desktop, "main.properties.txt");
Alernativly, if you plan to distribute configuration and property files that do not require user interaction, you may want to use locations like Temp or Documents (Windows).
2. Relative to the jar
Probably one of your best options. Assume the target is in the same folder than the jar-File (or at least in a fix structure relative to the jar). Here is how you access it (related question: how-to-get-the-path-of-a-running-jar-file):
CodeSource codeSource = YourMainClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
File jarDir = jarFile.getParentFile();
File target = new File(jarDir, "main.properties.txt");
I want to print the output in a file. I am using PrintWriter IO stream to add the data to file. When I want to check it, I don't know where the file is located. I am using Eclipse IDE.
PrintWriter writer=new PrintWriter("output.txt","UTF-8");
writer.println("Barcode Reader");
So can any one point me to where the file will be located?
I had this problem initially when I switched to using Eclipse. The current relative path is set to the project directory. The following code snippet will explain this better.
Path currentRelativePath = Paths.get("");
String myPath = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + myPath);
Note that the Path object is received from a get method in Paths((plural)). They are located in java.nio.file.
Further information about this can be found in the Path Operations page.
Does that solve your problem?
It will be present in your project's root folder.
Just open your project folder from your workspace using Explorer and it will be there.
With a filename like "output.txt" it will be placed into the current working directory.
Unless you specify otherwise, in Eclipse that will be the root directory of your project.
You may have to click "Refresh" for it to show up in the File Explorer.
If you give you file name directly like C:\java\workspace\ocpjp7 (a Windows
directory) or /home/nblack/docs (the docs directory of user nblack on UNIX), you can find your file in those directories. But if you don't give the full path, it will be in your current working directory.
"output.txt" -> root
"src/resources/output.txt" -> in resources package
At first you should create this file with File in directory you want.Next step to write data into the file. Your file will be located in directory you want , you set when file has created.
Also check this class FileInputStream
I'm working on a simple project, and i'm trying to get the absolute path of a file. This is what i'm trying:
String s = "file.txt";
System.out.println(new File(s).getAbsoluteFile().getAbsolutePath());
The output is:
C:\Users\Marcello\Desktop\Java Workspace\Simple Project\file.txt
Where "Simple Project" is the name of the project where the code is.
But the output should be:
C:\Users\Marcello\Desktop\file.txt
That is where i created the .txt file.
I also tryed with file.getCanonicalFile() and "file.getCanonicalPath()". And i've had the same issue.
In this project i'm using a text file, but i want it to work with folders too. So if someone knows a solution also for folder, i'd like to see it.
Sorry for my english but it's not my mother-tongue, thanks in advance.
EDITED:
I think the absolute path should be:
C:\Users\Marcello\Desktop\file.txt
Because i created the .txt file by right-clicking on the desktop....
Here is a screenshot of my desktop:
File is not an actual file, it is just a reference to a file path which may or may not exist. The file you created on your desktop has nothing to do with the File object you created in Java. The output is telling you, not where your expected file is, but where the File object's reference is going to go looking for it if you try to open the file.
To find an actual path to a file in an unknown location, you'll have search for it, as in "Recursively list files in Java".
Since you say that the file is in your current location, File just adds that in front of it. If you execute your program in another directory, the path would be something else. Java does not check if the file exists and java can't know where you created a file named that - and there might be multiple files named so.
If you want to access a file that is not in your current work directory (you can see that using System.getProperty("user.dir)), you need to give it a path in front of it - no matter if relative or absolute, but java can't guess where your file is.
The easiest way to do this for any file whether it be on the desktop or wherever would be to first browse for the file.
Second, select the file.
Third, use code to get the absolute file path of the file you selected.
To do that, you can use something like this:
JFileChooser choose = new JFileChooser();
choose.showOpenDialog(null);
File f = choose.getSelectedFile();
String filePath = f.getAbsolutePath();
Otherwise, IF AND ONLY IF your file is located on the desktop or if the desktop is somewhere in the file path, then you can use this:
File f = new File(System.getProperty("user.home") + "/Desktop" + "\\file.txt");
if(f.exists())
String filePath = f.getAbsolutePath();
Hope this helps!!
This code goes directly to the desktop and then gets the file you hardcoded in.
Okay, so I want to read a file name myfile.txt and let's say I'll be saving it under this directory:
home/myName/Documents/workspace/myProject/files myfile.txt
hmmm.. I want to know what I should pass on the File(filePath) as my parameter... Can I put something like "..\myfile.txt"? I don't want to hard code the file path, because, it will definitely change if say I open my project on another PC. How do i make sure that the filepath is as dynamic as possible? By the way, I'm using java.
File teacherFile = new File(filePath);
You can references files using relative paths like ../myfile.txt. The base of these paths will be the directory that the Java process was started in for the command line. For Eclipse it's the root of your project, or what you've configured as the working directory under Run > Run Configurations > Arguments. If you want to see what the current directory is inside of Java, here's a trick to determine it:
File currentDir = new File("");
System.out.println(currentDir.getAbsolutePath());
You can use relative paths, by default they will be relative to the current directory where you are executing the Java app from.
But you can also get the user's home directory with:
String userHome = System.getProperty("user.home");
You can do it:
File currentDir = new File (".");
String basePath = currentDir.getCanonicalPath();
now basePath is the path to your application folder, add it the exact dir / filename and you're good to go
You can use ../myfile.txt However the location of this will change depending on the working directory of the application. You are better off determining the base directory of you project is and using paths relative to that.
I have created a java application for "Debian Linux." Now I want that that application reads a file placed in the directory where the jar file of that application is specified. So what to specify at the argument of the File Object?
File fileToBeReaded = new File(...);
What to specify as argument for the above statement to specify relative filepath representing the path where the jar file of the application has been placed?
If you know the name of the file, of course it's simply
new File("./myFileName")
If you don't know the name, you can use the File object's list() method to get a list of files in the current directory, and then pick the one you want.
Are you asking about escape character issues?
If that is the case then use forward slashes instead of backward slashes like
"C:/Users/You/Desktop/test.txt"
instead of
"C:\Users\You\Desktop\test.txt"
Using relative paths in java.io.File is fully dependent on the current working directory. This differs with the way you execute the JAR. If you're for example in /foo and you execute the JAR by java -jar /bar/jar/Bar.jar then the working directory is still /foo. But if you cd to /bar/jar and execute java -jar Bar.jar then the working directory is /bar/jar.
If you want the root path where the JAR is located, one of the ways would be:
File root = new File(Thread.currentThread().getContextClassLoader().getResource("").toURI());
This returns the root path of the JAR file (i.o.w. the classpath root). If you place your resource relative to the classpath root, you can access it as follows:
File resource = new File(root, "filename.ext");
Alternatively you can also just use:
File resource = new File(Thread.currentThread().getContextClassLoader().getResource("filename.ext").toURI());
I think this should do the trick:
File starting = new File(System.getProperty("user.dir"));
File fileToBeRead = new File(starting,"my_file.txt");
This way, the file will be searched in the user.dir property, which will be your app's working directory.
You could ask your classloader to give you the location of the jar:
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
...but I'd suggest to put the file you are looking for inside your jar file and read it as a resource (getClass().getResourceAsStream( "myFile.txt" )).
On IntelliJIDEA right click on the file then copy the absolute path, then in the double quotation paste the path as filePath.
for example it should be something like this:
"C:\\Users\\NameOfTheComputerUser\\IdeaProjects\\NameOfTheProject\\YourSubFolders\\name-of-the-file.example"