Create whole path automatically when writing to a new file - java

I want to write a new file with the FileWriter. I use it like this:
FileWriter newJsp = new FileWriter("C:\\user\Desktop\dir1\dir2\filename.txt");
Now dir1 and dir2 currently don't exist. I want Java to create them automatically if they aren't already there. Actually Java should set up the whole file path if not already existing.
How can I achieve this?

Something like:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);

Since Java 1.7 you can use Files.createFile:
Path pathToFile = Paths.get("/home/joe/foo/bar/myFile.txt");
Files.createDirectories(pathToFile.getParent());
Files.createFile(pathToFile);

Use File.mkdirs():
File dir = new File("C:\\user\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newJsp = new FileWriter(file);

Use File.mkdirs().

Use FileUtils to handle all these headaches.
Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.
openOutputStream(File file [, boolean append])

Related

Creating Directories and Sub directories and getting files inside sub directories [duplicate]

I want to write a new file with the FileWriter. I use it like this:
FileWriter newJsp = new FileWriter("C:\\user\Desktop\dir1\dir2\filename.txt");
Now dir1 and dir2 currently don't exist. I want Java to create them automatically if they aren't already there. Actually Java should set up the whole file path if not already existing.
How can I achieve this?
Something like:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
Since Java 1.7 you can use Files.createFile:
Path pathToFile = Paths.get("/home/joe/foo/bar/myFile.txt");
Files.createDirectories(pathToFile.getParent());
Files.createFile(pathToFile);
Use File.mkdirs():
File dir = new File("C:\\user\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newJsp = new FileWriter(file);
Use File.mkdirs().
Use FileUtils to handle all these headaches.
Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.
openOutputStream(File file [, boolean append])

Writing to Files : Printwriter Converting Forward Slash to Backslash

Why is Printwriter doing this?
File file = new File("/files/KA.txt");
writer = new PrintWriter(file);
writer.write("HELLO");
In the above code I keep getting an error that says :
java.io.FileNotFoundException: \files\KA.txt (The network path was not found)
Except this was not my specified path? How do I then specify a file to write - usually create a new file and write to this? It also throws errors if KA.txt is not present - I ideally want to create a new file and writer to it.
Thanks
I ideally want to create a new file and writer to it.
You can simply create a file ,
PrintWriter writer = new PrintWriter("name.txt", "UTF-8");
writer.println("text");
where UTF-8 is the file encoding. and write to the file , remember it overrides if the file exists with the same name
The problem is that the parent /files directory doesn't already exist, so you must create it beforehand, using File.mkdirs.
File file = new File("/files/KA.txt");
File parentFile = file.getParentFile();
parentFile.mkdirs();
PrintWriter writer = new PrintWriter(file);
writer.write("HELLO");
writer.close();

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.

File creation methods

When I use the following code to create file, it doesn't output a visible file.It doesn't give any exception. In the following code output is exist. That means file is actually there exist. But I can't visible. Actually what is going on here?
File file= new File("/folder/abc.txt");
if(file.exist)
System.out.println("exist");
File file= new File("/folder/abc.txt");
NEVER creates an actual file.
There are two ways to create a file:
Invoke the createNewFile() method on a File object. For example:
File file = new File("foo"); // no file yet
file.createNewFile(); // make a file, "foo" which
// is assigned to 'file'
Create a Writer or a Stream. Specifically, create a FileWriter, a PrintWriter,
or a FileOutputStream. Whenever you create an instance of one of these
classes, you automatically create a file, unless one already exists, for instance
File file = new File("foo"); // no file yet
PrintWriter pw = new PrintWriter(file); // make a PrintWriter object AND
// make a file, "foo" to which
// 'file' is assigned, AND assign
// 'pw' to the PrintWriter
It's a file abstraction class, this doesn't create any file yet. From documentation:
An abstract representation of file and directory pathnames.
You can do lot more than creating a new file, for example checking if such file or directory exist.
Creating a File instance does not create a File on your file system.
You need to call a method of that instance to create the file on the file system
File f = new File("/folder/myfile");
if(!f.exists){
f.createNewFile();
}
As per Java docs,
Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.
creates only a instance.
Actual file is created by using file.createNewFile();
You are just creating a java object, you need to use:
File file= new File("/folder/abc.txt");
file.createNewFile();
For good practice check if file exists if not then create new one.
File file= new File("/folder/abc.txt");
if(!file.exists())
file.createNewFile();
File file= new File("/folder/abc.txt");
creates java File object, not real file. to create real file call:
file.createNewFile();
or use Stream. For example:
FileOutputStream stream = new FileOutputStream(file);
Just because you create an instance of java.io.File class, that file on the filesystem won't be created instantly.
You have to take steps to actually create it. You will find information easily on this.

Create File at user defined path

I am creating a file in java using
BufferedWriter out = new BufferedWriter(new FileWriter(FileName));
StringBuffer sb=new StringBuffer();
sb.append("\n");
sb.append("work");
out.write(sb.toString());
out.close();
But this file is getting created inside the bin folder of my server.I would like to create this file inside a user-defined folder.
How can it be achieved.
I would like to create this file inside a user-defined folder.
The simplest approach is to specify a fully qualified path name. You could select that as a File and build a new File relative to it:
File directory = new File("/home/jon/somewhere");
File fullPath = new File(directory, fileName);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
(new FileOutputStream(fullPath), charSet));
try {
writer.write("\n");
writer.write("work");
} finally {
writer.close();
}
Note:
I would suggest using a FileOutputStream wrapped in an OutputStreamWriter instead of using FileWriter, as you can't specify an encoding with FileWriter
Use a try/finally block (or try-with-resources in Java 7) so that you always close the writer even if there's an exception.
To create a file in a specific directory, you need to specify it in the file name.
Otherwise it will use the current working directory which is likely to be where the program was started from.
BTW: Unless you are using Java 1.4 or older, you can use StringBuilder instead of StringBuffer, although in this case PrintWriter would be even better.

Categories

Resources