Java FileOutputStream Default Creation Path - java

Let's say I have below code:
String fileName = "name.txt";
FileOutputStream fileOut = new FileOutputStream(fileName);
wb.write(fileOut);
This way, the file will be created under bin folder of the project.
However, if I specific fileName at a whole path:
String fileName = "c:/temp/name.txt";
this file will be created at c:\temp folder.
Am Correct? And Why this happen, how FileOutputStream work?

It's not about how FileOutputStream works, it's about the path that the operating system assigns to a process when it starts it
This path is called current working directory. From that directory all relative paths are calculated. A simple file name is a relative path (to the current working directory).
If you specify an absolute path then this path is used to create the file.
You can read more about paths on this wiki page.

If you don't specify an absolute path, e.g. if you only specify the file name, then your program or the operating system somehow needs to figure out, where to find that file. For that reason a running program always has a working directory. That happens to be the folder you start it from, by default.

Unless you specify an absolute path, the path is relative to current working directory.
If your current working directory is a bin folder in your project, it will be created there.

If you only specify the filename, it will be created in the current working directory. If you do specify an absolute path, it will of course be created at that path.

It's all about relative and absolute directories. Let's say that you specif path foo/bar. It'll create a file bar in foo directory of your working folder. The same applies for ../foo/bar it'll create a bar file in foo directory in the folder above the working dir. However, if you type C:\\Documents\ and\ Settings\User\Desktop\bar (or /home/user/Desktop/bar), it'll create a bar on your desktop. For more info take a look here.

Related

Java can't get relative path for file

Image DescriptionTrying to access a test.txt file that is in the same location as my HelloController.java file but for some reason, it is showing that the file does not exist. I've tried moving the file around but it does not work.
Using the absolute path works, but this is a shared project so it will be ran on other computers. Any suggestions would be much appreciated.
Your best bet is to add it to the class path and reading it as a class path resource.
The relative path root is your "working directory". Which means if you try to access "." you will start at your working directory. This directory is only set once for your application and is normally the folder which was opened when you started it.
When working with IDEs (like in your case) the working directory will be the root folder of your project (So the folder in which the pom.xml and src folders are located.
If you want to access the file via the normal file API you are currently using, just put the file in that diretory and it should work (given you share it with the other people in the same location).
If you need the file to be inside your generated output jar-file, you will need to use the File as a resource (See duffymo's answer), as the file does not exist by itself on the file system, but as a file inside your jar-file.
If you want to know your current working directory, you can create a File refrence to "." and expand it to an absolute path (Which will replace refrences like "." and ".." and generate a file path from your root) and then write it to the console. This would look something like this:
// Get refrence to the current working directory
File workingDirectoryReference = new File(".");
// Convert it to an absolute path string
String absolutePath = workingDirectoryReference.getAbsolutePath();
// Output to console
System.out.println(absolutePath );

Where the file will be located while using IO Streams in Java In Eclipse IDE?

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

relative path in Java

My program has to use certain files that reside in another directory. Right now I am using absolute path to specify the location of the files. But I know that the relative position of these files will remain the same compared to where my program is residing. How I can use relative path in Java to specify the location of these files?
For example my program is residing in
/home/username/project/src/com/xyz/
..and the target files are in..
/home/username/project/secure/
For example my program is residing in /home/username/project/src/com/xyz/
and the target files are in /home/username/project/secure/
Knowing the place where your program's source code resides does not help. What you need to know is the current directory of the program when it is executed. That could be literally anything. Even if you are launching the application from (for example) Eclipse, the application launcher allows you to specify the "current directory" for the child process in the Run configuration.
Your current path.
currentPath= /home/username/project/src/com/xyz/;
Relative path to "/home/username/project/secure/" folder is
relativePath= ../../../secure;
In Java you can use getParentFile() to traverse up the tree.
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
This will be safe as you are not using system dependent file separator (../)

Dynamic filepath in Java (writing and reading text files)

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.

How to specify filepath in java?

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"

Categories