Java make directory but not file - java

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....

Related

Trouble in creating file java

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:/");
}
}

Java - Create a file in the same directory as the .jar if it doesn't already exist

I am stuck at two parts really.
A) I need the program to find the directory of the RUNNING JAR FILE and check if there is a file called "credits.txt" in the same directory.
B) If not, it would create the file in the SAME DIRECTORY.
The main issue is not being able to get the path of my file.
Say the running jar file was in a folder called "Server", the program would save the name "Server" in a string and then check if a file exists in that string. If so, do nothing, otherwise create the file.
#Override
public void onEnable(){
getLogger().info(ChatColor.GREEN + "Credits has been enabled!");
File file = new File("Credits.txt");
//HERE I NEED THE PROGRAM TO CHECK WHAT DIRECTORY THE RUNNING JAR FILE IS FROM
if (file.exists(//IN THE SAME DIRECTORY AS THE RUNNING JAR FILE)){
getLogger().info(ChatColor.DARK_GREEN + "Credits File Exists");
}else{
getLogger().info(ChatColor.DARK_RED + "Credits File Doesn't Exist!");
//HERE IT NEEDS TO CREATE THE FILE IN THE SAME DIRECTORY OF THE JAR FILE "credits.txt"
}
If you're making a Bukkit plugin, you can use getDataFolder() in your main class. Then you can check if it exists and then create it if it doesn't.
public void onEnable(){
getLogger().info(ChatColor.GREEN + "Credits has been enabled!");
File pluginDirectory = getDataFolder(); //getting the data folder
if(!pluginDirectory.exists()){
pluginDirectory.mkdir(); //Creating the plugin data folder if it doesn't exist.
}
File file = new File(pluginDirectory+File.seperator+"Credits.txt"); //Credits.txt inside the plugin directory
if (file.exists()){ //Checking if Credits.txt exists
getLogger().info(ChatColor.DARK_GREEN + "Credits File Exists");
}else{
getLogger().info(ChatColor.DARK_RED + "Credits File Doesn't Exist!");
file.createNewFile(); //You probably need to create it too
}
}
If you want to create it for storing settings, consider using getConfig() instead of creating a file yourself. It's much easier.

Create ini file

I wounder how to make .ini file in Java. I know how to make .txt file, but how to make .ini file I don't. For reading and wrting I use ini4j lib and I thnik it works good. First I make some directory because of saving some data from user, then I want to make file and I get error java.io.FileNotFoundException for codeline ini.load(new FileReader(INI_PATH)); , that means that my code doesn't make .ini file in codeline File newFile = new File(newPath+"connect.ini"); . Please help me!
My code is:
String path =System.getProperty("user.home");
dir = new File(path+"/ProjectName");
String newPath=path+"/ProjectName";
if(dir.exists()){
System.out.println("DIRECTORY EXISTS");
}
else{
dir.mkdir();
}
newPath=newPath+"/";
File newFile = new File(newPath+"connect.ini");
INI_PATH = newFile.getAbsolutePath();
System.out.println("INI_PATH "+INI_PATH);
Wini ini = new Wini();
ini.load(new FileReader(INI_PATH));
...SOME CODE FOR ADDUING PAIRS....
You are getting a FileNotFoundException because the file does not exist on the disk, if you are trying to create the file in code use the following:
File newFile = new File(newPath+"connect.ini");
newFile.createNewFile();
the createNewFile() method on Java's File class will create a file if it doesn't exist, then you can feel free to use a FileReader or FileWriter to work with the newly created (but blank) file.

How to set file path to src folder of project

I want to make a program that you can email to someone and they can run it.
Right now my code for making a file is like this:
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml);
f.createNewFile();
But what if someones username is not S0urceC0ded, or they put the project in a different place? How could I set the file path to the src folder plus the filename?
Leave the path off entirely, it will use the directory of the project.
Change
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml");
To
File f = new File("axmlfile.xml");
I generally use code like this for temporary file storage, this way it gets cleaned up when the application finishes. If required you can allow the user to save a version of the file or move it to a permanent location.
try{
//create a temporary file
File temp = File.createTempFile("axmlfile", ".xml");
System.out.println("Location: " + temp.getAbsolutePath());
}catch(IOException e){
e.printStackTrace();
}

Problem with moving a file to another folder

I am using:
// File (or directory) to be moved
File file = new File(output.toString());
// Destination directory
File dir = new File(directory_name);
// Move file to new directory
boolean success = file.renameTo(new File(dir, new_file.getName()));
if (!success) {
// File was not successfully moved
}
In this case file is main.vm, and folder is seven
the program shows that it works(the file exists and all) but the file is not moving to the seven directory.
Any ideas why?
Is it ok that the file name is main.vm or do i need to enter full path? the same for the folder.
Thanks
Maybe you wanna take a look at the Apache Commons FileUtils
Works for me. (run with java -ea opt.)
File f = new File("foo.mv");
if(!f.exists())
assert f.createNewFile() : "failed to create foo.mv";
File folder = new File("7");
if(!folder.exists())
assert folder.mkdir() : "failed to create new directory";
File fnew = new File(folder, f.getName());
assert !fnew.exists() : "fnew already exists";
f.renameTo(fnew);
assert fnew.exists() : "fnew does not exist -- move failed";
System.out.format("moved %s to %s\n",f, fnew);
Try to do following steps:
check if you move the file inside same filesystem - otherwise it will fail;
create destination directory;
define "new_file" variable.
You need to enter full path of the file, not only the filename. And would be nice if you'll show up your full source code in the future, for better understanding/answers.

Categories

Resources