creating folders for all users - java

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();

Related

java create file in specific folder

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

Save a binary file in the same folder for every PC

I'm making a game that saves information into a binary file so that I can start at the point I left the game on the next use.
My problem is that it works fine on my PC because I chose a path that already existed to save the file, but once I run the game on another PC, I got an error saying the path of the file is invalid (because i doesn't exist yet, obviously).
Basically I'm using the File class to create the file and then the ObjectOutputStream and ObjectInputStream to read/write info.
Sorry for the noob question, I'm still pretty new to using files.
You must first check if the directory exists and if it does not exist then you must create it.
String folderPath = System.getProperty("user.home") + System.getProperty("file.separator") + "MyFolder";
File folder = new File(folderPath);
if(!folder.exists())
{
folder.mkdirs();
}
File saveFile = new File(folderPath, "fileName.ext");
Please note that the mkdirs() method is more useful in this case instead of the mkdir() method as it will create all non existing parent folders.
Hope this helps. Good luck and have fun programming!
Cheers,
Lofty
You are looking for File mkdirs()
Which will create all the directories necessary that are named in your path.
For example:
File dirs= new File("/this/path/does/not/exist/yet");
dirs.mkdir();
File file = new File(dirs, "myFile.txt");
Take in consideration that it may fail, due to proper file permissions.
My solution has been create a subdirectory within the user's home directory (System.getProperty("user.home")), like
File f = new File(System.getProperty("user.home") + "/CtrlAltDelData");
f.mkdir();
File mySaveFile = new File (f, "save1.txt");

Where i Can find text file created by servlet in Eclipse

This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.

How to open file in another directory in java?

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");

Java: How to create a new folder in Mac OS X

I want to create a folder in ex. my desktop in Mac OS X
I try to use this code, instead of Mymac is my name of course:)
String path="/Users/Mymac/Desktop";
String house = "My_home";
File file=new File(path);
if(!file.exists())
file.mkdirs(); // or file.mkdir()
file=new File(path + "/" + house);
try {
if(file.createNewFile())
{
}
} catch (IOException ex) {
ex.printStackTrace();
}
Do you know how I could create a new folder?
And another thing is when I want to create a folder in the directory where my code is, do you know how I could write that? I have tried
String path="./";
String path="::MyVolume";
String path=".";
A platform-independent way:
File rootDir = File.listRoots()[0];
File dir = new File(new File(new File(rootDir, "Users"), "Mymac"), "Desktop");
if (!dir.exists()){
dir.mkdirs();
}
Your code is ok and will work. Perhaps you have a typo in your username in your file-path ("Mymac"), so you don't see the changes, since they go to another folder.
Running this code on my machine works fine and gives the expected result.
To make your code platform-independant, you can build your file-path with the following trick:
File path = new File(File.listRoots()[0], "Users" + System.getProperty("file.separator") + "Mymac" + System.getProperty("file.separator") + "Desktop"));
If "My_home" should be a folder and not a file, you have to change the file.createNewFile() - command. More detailed information you'll find in the answer of Thomas.
To find the folder/directory where one of your classes is (assuming they are not in a Jar), and then to create a subfolder there:
String resource = MyClass.class.getName().replace(".", File.separator) + ".class";
URL fileURL = ClassLoader.getSystemClassLoader().getResource(resource);
String path = new File(fileURL.toURI()).getParent();
String mySubFolder = "subFolder";
File newDir = new File(path + File.separator + mySubFolder);
boolean success = newDir.mkdir();
(The code above could be made more compact, I listed it more verbosely to demonstrate all the steps.) Of course, you need to be concerned about permission issues. Make sure that the user which is running java has permission to create a new folder.
Use file.mkdir() or file.mkdirs() instead of file.createNewFile() and it should work, if you have permission to create new folders and files.
mkdirs() will create the subfolders if they don't exist, mkdir() won't.
To create a directory in your base directory (the one you start your application from), just provide a relative path name: new File("mydir").mkdir();
Edit: to make file handling easier, I'd suggest you also have a look at Apache Commons' FilenameUtils and FileUtils.

Categories