How to open a file that is not present in the current directory but in another directory. For example, I have a folder F:/test and my file is in F:/test/test2/doit.txt and D:/test3/doit2.txt
What to enter in path in parameter while making File object as follows :
File f = new File("/test2/doit.txt");
Irrespective of which operating system, a file for example, demo.txt can be accessed like
File file = new File("/d:/user/demo.txt");
in Windows where the file is at D:\user\ and
File file = new File("/usr/demo.txt");
in *nix or *nuxwhere the file is at /usr/
Also, a file if wanted to be accessed relatively can be done as (considering the Windows example) :
Suppose I am in the songs directory in D: like:
D:/
|
|---songs/
| |
| |---Main.java
|
|---user/
|
|---demo.txt
and the code is inside Main.java, then the following code works.
File file = new File("../user/demo.txt");
Assuming that you are running your program from F:/test you should use something like:
File f = new File("./test2/doit.txt");
Using hardcoded absolute paths isn't a good idea - your program might not work when user has different directory structure.
File inside of a project can be open as:
File file = new File(path);
or
File file = new File(./path);
where path is relative path from the project.
For example, when the project name is test and the file with name fileName is inside the test project:
File file = new File("fileName");
or
File file = new File("./fileName");
Please try the code below on Windows OS:
reader = new FileReader ("C:/Users/user/Desktop/java/test.txt");
Related
I am trying to create a folder by running java. As of now I have this and it works.
File f = new File ("/Users/myName/Desktop/nameOfDir");
f.mkdirs();
The question is what happens when I send this code to my friend? Would he have to change the code to the below for it to work?
File f = new File ("/Users/myFriendsName/Desktop/nameOfDir");
f.mkdirs();
how can I make the program find the correct path and create the folder where I want it (the desktop), regardless of who the user is?
Also, after creating the folder I will have to create a .txt in the folder. I can do this now, but same problem arise concerning different user names.
try using the following:
String userName = System.getProperty("user.name"); //platform independent
File f = new File ("/Users/" + userName + "/Desktop/nameOfDir");
f.mkdirs();
You can get the path to a user's home directory in a platform-independent way using:
System.getProperty("user.home");
So:
File f = new File(System.getProperty("user.home"), "Desktop/nameOfDir");
f.mkdirs();
I am trying to create a temp file in a specific folder
In the image below, you can find the structure tree of my project. I am currently in FileAnalyse.java and trying to create the file in data, under webcontent.
The following tries did not work for me:
File dir = new File(System.getProperty("user.dir")+"/WebContent/data");
File subjectFile = File.createTempFile("subjects", ".json",dir);
or
File dir = new File("/WebContent/data");
File subjectFile = File.createTempFile("subjects", ".json",dir);
File dir = new File("WebContent/data");
System.out.println(dir.getAbsolutePath()); //check the path with System.out
File subjectFile = File.createTempFile("subjects", ".json",dir);
This worked for me
note:
Your Version:
File dir = new File("/WebContent/data"); //has a / before WebContent
Correct Version:
File dir = new File("WebContent/data"); // no / before WebContent
Edit:
You can check if your path is the correct one with your attempts (or if you're on the right track to get the correct) when you print out the Path you're currently working with:
File dir = new File("YOUR/ATTEMPT");
System.out.println(dir.getAbsolutePath()); //check the path with System.out
that way you can check the absolute path, and you can look if the current attempted Pathstring is nearly correct
I solved the problem by changing the working directory of eclipse by going to run configurations->tomcat->change working directory
I have a file dateTesting.java . the path's directory is as follows: D:\workspace\Project1\src\dateTesting.java . I want the full path of this file as "D:\workspace\Project1\src" itself but when I use any of the following code, i get only "D:\workspace\Project1" . the src part is not coming.
System.out.println(System.getProperty("user.dir"));
File dir2 = new File(".");
System.out.println(dir2.getCanonicalPath().toString());
System.out.println(dir2.getAbsolutePath());
How can I get the full path as "D:\workspace\Project1\src" ? I'm using eclipse ide 3.5
Thank you
dateTesting.java is a Java source file which is not available after compilation to bytecode. The source directory it was in is not available, too.
dir2 is the File of the directory you execute the .class file in. It seams that this happens to be D:\workspace\Project1 but you can't rely on this.
Your dir2 points to working directory (new File(".")). You can't get the location of your sources this way. Your file could sit inside the package (e.g. your.company.date.dateTesting). You should just manually concat the "src" to current working directory and then replace file package dots (.) with File.pathSeparator. In that way you will build the full path to your file.
String fullFilePath = "H:\\Shared\\Testing\\abcd.bmp";
File file = new File(fullFilePath);
String filePath = file.getAbsolutePath().substring(0,fullFilePath.lastIndexOf(File.separator));
System.out.println(filePath);
Output:
H:\Shared\Testing
If you are doing this to try to read a file from the classpath, then check out this answer:
How to really read text file from classpath in Java
Essentially you can do this
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
Otherwise, if you have some other requirement, one option is to pass through the src directory as a JVM arg when the application begins and then just read it back.
/** The actual file running */
public static final File JAR_FILE = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
/** The path to the main folder where the file .jar is run */
public static final String BASE_DIRECTORY = (JAR_FILE != null ? JAR_FILE.getAbsolutePath().replace(JAR_FILE.getName(), "") : "notFound");
This will work for you both in normal java execution and jar execution. This is the solution I am using in my project.
I am making a program that opens and reads a file.
This is my code:
import java.io.*;
public class FileRead{
public static void main(String[] args){
try{
File file = new File("hello.txt");
System.out.println(file.getCanonicalPath());
FileInputStream ft = new FileInputStream(file);
DataInputStream in = new DataInputStream(ft);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline;
while((strline = br.readLine()) != null){
System.out.println(strline);
}
in.close();
}catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
but when I run, I get this error:
C:\Users\User\Documents\Workspace\FileRead\hello.txt
Error: hello.txt (The system cannot find the file specified)
my FileRead.java and hello.txt where in the same directory that can be found in:
C:\Users\User\Documents\Workspace\FileRead
I'm wondering what I am doing wrong?
Try to list all files' names in the directory by calling:
File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);
and see if you will find your files in the list.
I have copied your code and it runs fine.
I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by #Eng.Fouad
You need to give the absolute pathname to where the file exists.
File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
In your IDE right click on the file you want to read and choose "copy path"
then paste it into your code.
Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"
Generally, just stating the name of file inside the File constructor means that the file is located in the same directory as the java file. However, when using IDEs like NetBeans and Eclipse i.e. not the case you have to save the file in the project folder directory. So I think checking that will solve your problem.
How are you running the program?
It's not the java file that is being ran but rather the .class file that is created by compiling the java code. You will either need to specify the absolute path like user1420750 says or a relative path to your System.getProperty("user.dir") directory. This should be the working directory or the directory you ran the java command from.
First Create folder same as path which you Specified. after then create File
File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");
if(!file.exists())
{
dir.mkdir();
file.createNewFile();
System.out.println("File,Folder Created.);
}
When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.
I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].
I know how to create a temporary directory in Java, but is there an easy way to copy files in Java from the jar file to this directory?
File tmpDir = new File(System.getProperty("java.io.tmpdir"));
File helpDir = new File(tmpDir, "myApp-help");
helpDir.createNewFile(); // oops, this isn't right, I want to create a dir
URL helpURL = getClass().getResource("/help-info");
/* ???? I want to copy the files from helpURL to helpDir */
Desktop desktop = Desktop.getDesktop();
URI helpURI = /* some URI from the new dir's index.html */
desktop.browse(helpURI);
Apache's org.apache.commons.io.FileUtils can do that for you
To create directory use File.mkdir();
Convert URL to File with org.apache.commons.io.FileUtils.toFile(URL)
use org.apache.commons.io.FileUtils.copyFile() to copy.
You can make use of the command jar tf [here your jarfile]. This will list the contents of the JAR Archive with their full path, relative to the jarfile (1 line = 1 file). Check if the line starts with the path of the directory you want to extract, and use Class.getResourceAsStream(URL) for the matching lines and extract them to your temporary folder.
Here is an example output of jar tf:
META-INF/MANIFEST.MF
TicTacToe.class
audio/
audio/beep.au
audio/ding.au
audio/return.au
audio/yahoo1.au
audio/yahoo2.au
images/
images/cross.gif
images/not.gif