when I new a File Object ,I found that there is not a file be create in disk,so I guess a File Obeject is not equal to a disk file, but when I write something to the File object through stream, I found the file be created in disk.
So, can I think like this, new File() - does not create a real file in disk, it is just an object in ram. But when you write something to the File through stream, for example:
FileWrite stream = new FileWrite(file);
stream.write(string);
..the stream will create a new file when the file does not exist (maybe function steam.write() does this?)?
How about File#createNewFile()? If you're using Java 7, you can also use Files.createFile(Path), as in this example from the Java tutorial.
FileWriter creates or truncates the file as required. The write put something in it. File is a file path name which may or may not exist. e.g. File.exists() is not always true and File.delete() can delete a file (i.e. the file no longer exists)
Related
I'm working with the FileOutputStream class in java, but I don't know how to delete "the contents" of a file (the main reason i need overwrite the file).
If you want to delete the contents of the file, but not the file itself, you could do:
PrintWriter pw = new PrintWriter("file.txt");
pw.close();
A few seconds of Googling got me this:
how to delete the content of text file without deleting itself
How to clear a text file without deleting it?
To delete the file completely, do:
File file = new File("file.txt");
f.delete();
Call File.delete() which deletes the file or directory denoted by this abstract pathname.
File f = new File("foo.txt");
if (f.delete()) {
System.out.println("file deleted");
}
The main reason i need overwrite the file ...
One way to do this is to delete the file using File.delete() or Files.delete(Path). The latter is preferable, since it can tell you why the deletion fails.
The other way is to simply open the file for writing. Provided that you don't open in "append" mode, opening a file to write will truncate the file to zero bytes.
Note that there is a subtle difference in the behavior of these two approaches. If you delete a file and then create a new one, any other application that has the same file open won't notice. By contrast, if you truncate the file, then other applications with the file open will observe the effects of the truncation when they read.
Actually, this is platform dependent. On some platforms, a Java application that tries to open a file for reading that another file has open for writing will get an exception.
Yes, you can do it with FileOutputStream. All the answers given say about PrintWriter but the same can be done with FileOutputStream. The int representation of space is 32. So simply pass the file to the instance of FileOutputStream as:
FileOutputStream out = new FileOutputStream(file);
out.write(32);
This will clear the contents of the file. Surely use this only of u want to do it with FileOutputStream only otherwise use PrintWriter.
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
new File("abc.txt") does not create actual file while new FileWriter("abc.txt") creates a file on disk. While going through source code i found that new FileWriter("abc.txt") eventually creates an object of file like new File()
Constructor of Class java.io.File does not create file on disk. It is just a abstraction over the file path. The file is created when you write to the file.
When you are creating FileWriter it calls constructor of FileOutputStream that calls a sequence of security checks and then invokes:
if (append) {
openAppend(name);
} else {
open(name);
}
Invocation of open() creates file on disk.
EDIT:
Here is how open() is defined:
/**
* Opens a file, with the specified name, for writing.
* #param name name of file to be opened
*/
private native void open(String name) throws FileNotFoundException;
I think file.createNewFile() creates the new file in actual.. please see following code for detal...
File file = new File("D:\\tables\\test.sql");
// if file does not exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
File doesn't always need to represent an actual file, it can be something you plan on creating, are guessing at the existence of, or something you've deleted as well.
From the JavaDoc for java.io.File:
An abstract representation of file and directory pathnames.
and
Instances of this class may or may not denote an actual file-system object such as a file or a directory.
In order to have the file actually be created, one needs to call createNEwFile(), whic according to the JavaDoc:
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.
The File object is simply a representation of a file's location (URL) in the system. You can call createNewFile() on a File object in order to write our a file assuming one with that name does not already exist in that location.
When FileWriter creates a new File object internally, this is not what causes the file to come into existence. That happens in other parts of the code. A File object is just a standard way to designate a file (or directory), whether or not it exists.
There are lots of reasons really, but:
File is used by many classes in java.io. FileReader, etc... FileWriter is a "convenience" class that uses File and it enables the programmer to be more productive. Some Classes just want a File object which points to a file location and then they operate on it as needed to support their processing. Other Classes might support a FileWriter because it will only be writing to a file and not reading. It also makes the API more strongly-typed.
In a unit test I am overwriting a config file to test handling bad property values.
I am using Apache Commons IO:
org.apache.commons.io.FileUtils.copyFile(new File(configDir, "xyz.properties.badValue"), new File(configDir, "xyz.properties"), false)
When investigating the file system I can see that xyz.properties is in fact overwritten - size is updated and the content is the same as that of xyz.properties.badValue.
When I complete the test case which goes through code that reads the file into a Properties object (using a FileReader object) I get the properties of the original xyz.properties file, not the newly copied version.
Through debugging where I single step and investigate the file I can rule out it being a timing issue of writing to the file system.
Does the copy step somehow hold a file handle? If so how would I release it again?
If not, does anybody have any idea why this happens and how to resolve it?
Thanks.
If you initialized the FileReader object before this object, then it will have already stored a temp copy of the old version.
You'll need to reset it:
FileReader f = new FileReader("the.file");
// Copy and overwrite "the.file"
f = new FileReader("the.file");
In the Unix filesystem model, the inode containing the file's contents will persist as long as someone has an open filehandle into the file, or there is a directory entry pointing to it.
Replacing the file's name in the directory, does not remove the inode (contents of the file), so your already-open filehandle can continue to be used.
This is actually exploitable to create temporary files that never need to be cleaned up: create the file, then unlink it immediately, while keeping it open. When you close the file handle, the inode is reaped
I realize that this doesn't answer your question directly, but I think that it would be better to maintain two separate files, and arrange for your code to have the name of the configuration file configurable / injected at runtime. That way, your tests can specify which config file to use, rather than overwriting a single file.
I have a question regarding to the Java File class. When I create a File instance, for example,
File aFile = new File(path);
Where does the instance aFile store in the computer? Or it stores in JVM? I mean is there a temp file stored in the local disk?
If I have an InputStream instance, and write it to a file by using OutputSteam, for example
File aFile = new File("test.txt");
OutputStream anOutputStream = new FileOutputStream(aFile);
byte aBuffer[] = new byte[1024];
while( ( iLength = anInputStream.read( aBuffer ) ) > 0)
{
anOutputStream.write( aBuffer, 0, iLength);
}
Now where does the file test.txt store?
Thanks in advance!
A File object isn't a real file at all - it's really just a filename/location, and methods which hook into the file system to check whether or not the file really exists etc. There's no content directly associated with the File instance - it's not like it's a virtual in-memory file, for example. The instance itself is just an object in memory like any other object.
Creating a File instance on its own does nothing to the file system.
When you create a FileOutputStream, however, that does affect whatever file system you're writing to. The File instance is relatively irrelevant though - you'd get the same effect from:
OutputStream anOutputStream = new FileOutputStream("test.txt");
It will write the file where you specify it with path arguement.
In your case, it will write it in the directory where you run your java class.
If you specify /test/myproject/myfile.txt
it will go in /test/myproject/myfile.txt
If you don't provide a path, it is in the current directory (ie: the directory where java.exe is executed from.) If you provide a full path, it is stored there.
Regardless, it is always stored in the filesystem, not in JVM memory.