Can not create a temporary file - java

I am using this piece of code to create a temporary file:
String tmpDirectoryOp = System.getProperty("java.io.tmpdir");
File tmpDirectory = new File(tmpDirectoryOp);
File fstream = File.createTempFile("tmpDirectory",".flv", tmpDirectory);
FileOutputStream fos = new FileOutputStream(fstream);
DataOutputStream dos=new DataOutputStream(fos);
dos.writeChars("Write something");
fstream.deleteOnExit();
fos.close();
dos.close();
But there is no tmpDirectory.flv in my project folder. The write sentence is in a loop, which takes quite long time to finish, so the problem is not that the file is deleted before I could see it.
Any idea? Thanks in advance

Creates an empty file in the default
temporary-file directory, using the
given prefix and suffix to generate
its name. Invoking this method is
equivalent to invoking
createTempFile(prefix, suffix, null).
You can get temp dir for your operating system using
System.getProperty("java.io.tmpdir");
You have executed deleteOnExit()
public void deleteOnExit()
Requests that the file or directory
denoted by this abstract pathname be
deleted when the virtual machine
terminates. Deletion will be attempted
only for normal termination of the
virtual machine, as defined by the
Java Language Specification. Once
deletion has been requested, it is not
possible to cancel the request. This
method should therefore be used with
care.
Note: this method should not be used
for file-locking, as the resulting
protocol cannot be made to work
reliably. The FileLock facility should
be used instead.
Documentation

!! Please close the streams !!
File fstream = File.createTempFile("tmpDirectory",".flv");
FileOutputStream fos = new FileOutputStream(fstream);
DataOutputStream dos=new DataOutputStream(fos);
dos.writeChars("Write something");
fstream.deleteOnExit();
**
fos.close();
dos.close();
**

Have you looked in your /tmp folder?
If you want to create a temporary file in a specified folder, you need the 3 param createTempFile function

Try to flush and close the stream.

Related

How to delete the contents of a file using the FileOutputStream class in Java?

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.

Do I need to delete tmp files created by my java application?

I output several temporary files in my application to tmp directories but was wondering if it is best practise that I delete them on close or should I expect the host OS to handle this for me?
I am pretty new to Java, I can handle the delete but want to keep the application as multi-OS and Linux friendly as possible. I have tried to minimise file deletion if I don't need to do it.
This is the method I am using to output the tmp file:
try {
java.io.InputStream iss = getClass().getResourceAsStream("/nullpdf.pdf");
byte[] data = IOUtils.toByteArray(iss);
iss.read(data);
iss.close();
String tempFile = "file";
File temp = File.createTempFile(tempFile, ".pdf");
FileOutputStream fos = new FileOutputStream(temp);
fos.write(data);
fos.flush();
fos.close();
nopathbrain = temp.getAbsolutePath();
System.out.println(tempFile);
System.out.println(nopathbrain);
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("TEMP FILE NOT CREATED - ERROR ");
}
createTempFile() only creates a new file with a unique name, but does not mark it for deletion. Use deleteOnExit() on the created file to achieve that. Then, if the JVM shuts down properly, the temporary files should be deleted.
edit:
Sample for creating a 'true' temporary file in java:
File temp = File.createTempFile("temporary-", ".pdf");
temp.deleteOnExit();
This will create a file in the default temporary folder with a unique random name (temporary-{randomness}.pdf) and delete it when the JVM exits.
This should be sufficient for programs with a short to medium run time (e.g. scripts, simple GUI applications) that do sth. and then exit. If the program runs longer or indefinitely (server application, a monitoring client, ...) and the JVM won't exit, this method may clog the temporary folder with files. In such a situation the temporary files should be deleted by the application, as soon as they are not needed anymore (see delete() or Files helper class in JDK7).
As Java already abstracts away OS specific file system details, both approaches are as portable as Java. To ensure interoperability have a look at the new Path abstraction for file names in Java7.

File deletion with delete() method in Java

I have a little doubt about following code:
try {
File file = new File("writing");
file.createNewFile();
System.out.println(file.delete());
System.out.println(file.exists());
PrintWriter pw = new PrintWriter(file);
pw.print(324.2342);
pw.flush();
pw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
System.out.println(br.readLine());
br.close();
} catch(IOException ioE) {
System.out.println("Indeed");
}
Why in this circumstance the method file.delete() apparently says that it works as it returns "true" when executed and it gets also confirmed by the file.exists() method which returns "false". However at runtime I do not get any exception like "IOException the file "writing" does not exist" or something likewise.
Why does the file keep staying in the heap even though deleted physically? Shouldn't it be automatically garbage collected as soon as the delete method gets called? I know it does not because I saw the output.
This is because the File represents a abstract path, see the JavaDoc for it http://docs.oracle.com/javase/6/docs/api/java/io/File.html. It does not represent a file handle in the OS.
The line in your code:
PrintWriter pw = new PrintWriter(file);
Simply creates a new file. Try deleting the file after calling this...
File object represents a path to a physical file on the file system either exists or not. That's why you have exists() (to check if it exists) and createNewFile() (to create the file if it is not found).
Also note that PrintWriter(File file) creates a new file if it does not exist.
Parameters:
file - The file to use as the destination of this writer. If the file
exists then it will be truncated to zero size; otherwise, a new file
will be created. The output will be written to the file and is
buffered.
The File is handle to real file (that exists or not). You create and then delete the file above, as you say - all good so far.
When you come to the PrintWriter later on it creates the file once more when you use it - it doesnt matter that you deleted it before.
In fact depending on your use case this might be exaclty wht you want - you may want to delete an old log file for example before re-createing and writing to it once more.
Finally, nothing in your code will be eligible for garbage collection until your method exist, and even then the underyling file will continue to exist (if you dont delete it agin) - and any garbage colleciton in this case wouldnt effect the underlying file. It'll be deleted after the delete invokation and exist again once youre PrintWriter is done with it.
Hope this helps!
The file doesn't have a link to a particular file, rather to any file pointer by the file's path. With this line you're creating a new file:
PrintWriter pw = new PrintWriter(file);

FileOutputStream does not create file

I actually checked other posts that could be related to this and I couldn't find any answer to my question. So, had to create this newly:
The file does not get created in the given location with this code:
File as = new File ("C:\\Documents and Settings\\<user>\\Desktop\\demo1\\One.xls");
if (!as.exists()) {
as.createNewFile();
}
FileOutputStream fod = new FileOutputStream(as);
BufferedOutputStream dob = new BufferedOutputStream(fod);
byte[] asd = {65, 22, 123};
byte a1 = 87;
dob.write(asd);
dob.write(a1);
dob.flush();
if (dob!=null){
dob.close();
}
if(fod!=null){
fod.close();
The code runs fine and I don't get any FileNotFoundException!!
Is there anything that I'm missing out here?
You can rewrite your code like this:
BufferedOutputStream dob = null;
try {
File file = new File("C:\\Documents and Settings\\<user>\\Desktop\\demo1\\One.xls");
System.out.println("file created:" + file.exists());
FileOutputStream fod = new FileOutputStream(file);
System.out.println("file created:" + file.exists());
BufferedOutputStream dob = new BufferedOutputStream(fod);
byte[] asd = {65, 22, 123};
byte a1 = 87;
dob.write(asd);
dob.write(a1);
//dob.flush();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
if (dob != null) {
dob.close();
}
}
In this case it is only necessary to call the topmost stream handler close() method - the BufferedOutputStream's one:
Closes this output stream and releases any system resources associated with the stream.
The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.
so, the dob.flush() in try block is commented out because the dob.close() line in the finally block flushes the stream. Also, it releases the system resources (e.g. "closes the file") as stated in the apidoc quote above. Using the finally block is a good practice:
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
The FileOutputStream constructor creates an empty file on the disk:
Creates a file output stream to write to the file represented by the specified File object. A new FileDescriptor object is created to represent this file connection.
First, if there is a security manager, its checkWrite method is called with the path represented by the file argument as its argument.
If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.
Where a FileDescriptor is:
Instances of the file descriptor class serve as an opaque handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes. The main practical use for a file descriptor is to create a FileInputStream or FileOutputStream to contain it.
Applications should not create their own file descriptors.
This code should either produce a file or throw an exception. You have even confirmed that no conditions for throwing exception are met, e.g. you are replacing the string and the demo1 directory exists. Please, rewrite this to a new empty file and run.
If it still behaving the same, unless I have missed something this might be a bug. In that case, add this line to the code and post output:
System.out.println(System.getProperty("java.vendor")+" "+System.getProperty("java.version"));
Judging from the path, I'd say you are using Win 7, am I right? What version?
Then it means there is a file already in your directory

What is equivalent of fopen_s() in java?

I want to convert this code in java
fopen_s(&stream, "path", "w+");
w+ opens empty file with both reading and writing. If the given file exists, it's contents are destroyed.
any suggestions?
It seems 1.7 java is required for the nio, so my take is
RandomAccessFile f = new RandomAccessFile(name, "rw");
f.setLength(0);
I am not a Java programmer, but I had a short hunt around the web and it seems Java has a RandomAccessFile and you open it with the mode "rw".
The true equivalent is to use Files.newByteChannel.
final SeekableByteChannel channel = Files.newByteChannel(Paths.get("path"),
StandardOpenOptions.READ, StandardOpenOptions.WRITE,
StandardOpenOptions.TRUNCATE_EXISTING);
The READ and WRITE options determine if the file should be opened for reading and/or writing.
...
TRUNCATE_EXISTING - If this option is present then the existing file is truncated to a size of 0 bytes. This option is ignored when the file is opened only for reading.
Looks like you want either FileOutputStream or FileWriter, depending on what kind of data you want to write. Either of them can be instantiated with a filename.
FileOutputStream fis = new FileOutputStream("/path/to/file");
FileWriter fw = new FileWriter("/path/to/file2");
And both will clobber the file if it already exists. (Though constructors exists for appending instead of over-writing)
Quick way to achieve what you want:
import java.io.*;
// Create a new file output connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");
// Create a new file input connected to "myfile.txt"
in = new FileInputStream("myfile.txt");
You might want to take a look at the java.io package at the official docs, especially the RandomAccessFile Class and also this quick guide.

Categories