FileNotFound exception when trying to write to a file - java

OK, I'm feeling like this should be easy but am obviously missing something fundamental to file writing in Java. I have this:
File someFile = new File("someDirA/someDirB/someDirC/filename.txt");
and I just want to write to the file. However, while someDirA exists, someDirB (and therefore someDirC and filename.txt) do not exist. Doing this:
BufferedWriter writer = new BufferedWriter(new FileWriter(someFile));
throws a FileNotFoundException. Well, er, no kidding. I'm trying to create it after all. Do I need to break up the file path into components, create the directories and then create the file before instantiating the FileWriter object?

You have to create all the preceding directories first. And here is how to do it. You need to create a File object representing the path you want to exist and then call .mkdirs() on it. Then make sure you create the new file.
final File parent = new File("someDirA/someDirB/someDirC/");
if (!parent.mkdirs())
{
System.err.println("Could not create parent directories ");
}
final File someFile = new File(parent, "filename.txt");
someFile.createNewFile();

You can use the "mkdirs" method on the File class in Java. mkdirs will create your directory, and will create any non-existent parent directories if necessary.
http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#mkdirs%28%29

Related

Is using the File class in Java how you create a file?

I need some serious help with concepts. I have been given background context on the class, specifically this:
I just need to understand the purpose of this class? Can I create a text file (or any other type of file) with its constructors? Is this just for handling files, if so, what does that mean?
Any help whatsoever will be greatly appreciated!
Thank you
You could use the java.io.File to create a file on the file system:
File myFile = new File("myFile.txt");
myFile.createNewFile();
Note that invoking the constructor won't create the file on the file system. To create an empty file, the createNewFile() method has to be invoked.
The File simply represents a abstraction of the file location, not the file itself. It comes with operations on the file identified by the path: exists(), delete(), length(), etc.
What you probably want is to use the classes that allow you to write content to a file:
If you are to write text, you should use the Writer interface.
If you are to write binary content, you should use the OutputStream interface.
The classes FileWriter and FileOutputStream are, respectively, the ones that link the File and Writer/OutputStream concepts together. Those classes create the file on the file-system for you.
FileWriter myFileWriter = null;
File myFile = new File("myFile.txt");
try {
// file is created on the file-system here
myFileWriter = new FileWriter(myFile);
myFileWriter.write("hello");
} finally {
if (myFileWriter != null) {
myFileWriter.close();
}
}
You can create a file using the File.createNewFile method, or, if you are using Java 7 or newer, using the newer Files.createFile method.
The difference between the old File and the new Path classes is that the former mixed a reference to a path to a file on the filsystem and operations you can do on it, and the latter is just representing the path itself but allows you to query it and analyze its structure.

Android get file using path (in String format)

My app needs to get an existing file for processing. Now I have the path of the file in String format, how can I get the File with it? Is it correct to do this:
File fileToSave = new File(dirOfTheFile);
Here dirOfTheFile is the path of the file. If I implement it in this way, will I get the existing file or the system will create another file for me?
That's what you want to do. If the file exists you'll get it. Otherwise you'll create it. You can check whether the file exists by calling fileToSave.exists() on it and act appropriately if it does not.
The new keyword is creating a File object in code, not necessarily a new file on the device.
I would caution you to not use hardcoded paths if you are for dirOfFile. For example, if you're accessing external storage, call Environment.getExternalStorageDirectory() instead of hardcoding /sdcard.
The File object is just a reference to a file (a wrapper around the path of the file); creating a new File object does not actually create or read the file; to do that, use FileInputStream to read, FileOutputStream to write, or the various File helper methods (like exists(), createNewFile(), etc.) for example to actually perform operations on the path in question. Note that, as others have pointed out, you should use one of the utilities provided by the system to locate directories on the internal or external storage, depending on where you want your files.
try this..
File fileToSave = new File(dirOfTheFile);
if(fileToSave.exists())
{
// the file exists. use it
} else {
// create file here
}
if parent folder is not there you may have to call fileToSave.getParentFile().mkdirs() to create parent folders

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.

Java, how to check the existence of file

I have this small code
File source;
if ( !source.exists() ) {
source = new File("instances/student"+student.getStudentID()+".data");
}
The problem is, source is not initialized. Since the whole point is to check if it exists, how do I avoid this?
Create a File object.
File source = new File(...);
What constructor you use depends on how you want to locate a file. A simple path String could be enough.
EDIT: just realized the source of your confusion may be that you think creating the File object will try to locate the file or create it on the file system. That's not the case. Just calling new File(...) won't check its existence or try to create it. A File object is simply an abstraction for a path in your file system. It could be a directory as well.
You can do:
File f = new File(somepathhere);
if ( !f.exists() ) {
f = new File("instances/student"+student.getStudentID()+".data");
}
Or you can check if f.isFile()
You seem to have a misunderstanding. Creating a File doesn't create a file on the file system. A File object only really represents a filename. If you want to see whether a file exists, create a File of the appropriate name and check exists().
But then if you want to overwrite or append to a file you don't even need all that. Just create a new FileOutputStream(...), with the append parameter set to true if you want to append. No need to check beforehand, in fact it is more than a waste of time.

Java, create a file and a folder

I am creating files with Java in Windows. This works:
String newFile = "c:/"+Utilities.timeFormat();
...
some code that creates a folder
This does not work:
String newFile = "c:/newDirectory/"+Utilities.timeFormat();
...
some code that creates a folder
You have to use File.mkdir() or File.mkdirs() method to create a folder.
EDIT:
String path="c:/newDirectory";
File file=new File(path);
if(!file.exists())
file.mkdirs(); // or file.mkdir()
file=new File(path + "/" + Utilities.timeFormat());
if(file.createNewFile())
{
}
without knowing your actual code which is creating the directory:
use mkdirs() instead of mkdir()
Can you check that you have permissions to create a folder in c:/?
Can you show us the stacktrace too?
If "newDirectory" doesn't exist yet, you should use the method mkdirs() from the File class to create all the directories in between.
The fact that the directory doesn't exist is probably why it isn't working he first time through. As many have pointed out use mkdirs() will ensure if the file you want to write is in subfolders it will create them. Now here is what it might look like:
File file = new File( new File("c:/newDirectory"), Utilities.timeFormat() );
if( !file.getParentFile().exists() ) {
file.getParentFile().mkdirs();
}
OutputStream stream = new BufferedOutputStream( new FileOutputStream( file ) );
try {
// put your code here to write the file
} finally {
stream.close();
}
Notice I'm not using + to create a path. Instead I create a File object, and pass it the parent File and the name of the file. Also notice I'm not putting path separators in between the parent and filename. Using the File constructor takes care of a system independent way of creating paths.

Categories