open temp file in java - java

I'm writing string to temporary file (temp.txt) and I want that file should open after clicking button of my awt window it should delete when I close that file (after opening that file), how can I do this?
This is the code that I have been using to create temporary file in Java:
File temp = File.createTempFile("temp",".txt");
FileWriter fileoutput = new FileWriter(temp);
Bufferedwriter buffout = new BufferedWriter(fileoutput);

A file created by:
File temp = File.createTempFile("temp",".txt");
Will not be deleted, see javadoc, you have to call
temp.deleteOnExit();
so the JVM will delete the file on exit...

How about something like:
if (!temp.delete())
{
// wasn't deleted for some reason, delete on exit instead
temp.deleteOnExit();
}

Some links that might help you:
File.getAbsoluteFile()/getAbsolutePath().
FileReader.
File.delete().

To perform an operation when clicking a button, you will need code something like this:
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent event) {
fileOperation();
}
}
...
private void fileOperation() {
... do stuff with file ...
}
You can probably find many examples with google. Generally the anonymous inner class code should be short and just translate the event and context into operations meaningful to the outer class.
Currently you need to delete the file manually with File.delete after you have closed it. If you really wanted to you could extends, say, RandomAccessFile and override close to delete after the close. I believe delete-on-close was considered as a mode for opening file on JDK7 (no idea if it is in or not).
Just writing to a file, as in your code, would be pointless. You would presumably want to delete the file after closing a read stream no the write stream. It's not a bad idea to avoid temporary files if you possibly can.

Related

How i can make a Watch Service that deletes a file when it closes?

I basically want to make a watch service (or something like it) that checks if a file has been closed and instantly remove that file if it did close(finished executing).
How I can achieve this? please give me a cmd commands or some code(i prefer Java).
Ok, this should not be hard to do, if you google a bit you find a Java-File Method called file.canWrite() which basically returns if a file is locked by an other program or so.
So codewise what you could do is something like this.
boolean isDeleted = false;
File f = new File (// Put your file here);
while (!isDeleted) {
if (f.canWrite()) {
f.delete();
isDeleted = true;
} else {
try {
Thread.sleep(10); // Throws Exception you need to catch somewhere...
} catch (Exception e) {}
}
}
This code you need to include into some Java-Program. I added a simple Thread.sleep(10) that your PC does not have to check aaaaaalllllllll the time.
See Check if a file is locked in Java
Other possibility would be trying to rename the file with file.renameTo("some_path.txt"); as this method also returns a boolean whether it was successfull! Just note that you then need to update the file again before removing it.
Last possibility I see is pretty similar to the second one. You try to delete the file by calling file.delete(); If the file still exists you know it was not successful and loop because of that.
I assume you mean when the file is not open in another program, and you cannot make changes to that other program? (If you are talking about your own program opening the file, this is much easier.)
On Windows, it is not very easy to tell which program has a file open. Take a look at https://superuser.com/questions/117902/find-out-which-process-is-locking-a-file-or-folder-in-windows for some options. I like the handle tool for this, but it has to run as Administrator, which may be a problem. You can try renaming or writing to the file, as suggested at Check if a file is locked in Java
Once you have a script that determines whether the file is open to your satisfaction, it should be fairly straightforward to write a script which loops while testing if the file is open and then deletes file.

How to write to file synchronously using java?

I just started learning Java and I was interested in the File libraries. So I kept a notepad file open called filename.txt. Now I want to write to file using Java, but I want to get the result in real time.
I.e when the java code executes the changes should be visible in the text file without closing and reopening the file.
Here my code:
import java.io.*;
class Locker
{
File check = new File("filename.txt");
File rename = new File("filename.txt");
public void checker()
{
try{
FileWriter chk = new FileWriter("filename.txt");
if(check.exists())
{
System.out.println("File Exists");
chk.write("I have written Something in the file, hooray");
chk.close();
}
}
catch(Exception e)
{
}
}
};
class start
{
public static void main(String[] args)
{
Locker l = new Locker();
l.checker();
}
}
Is it possible and if so can someone tell me how?
Simple answer: this doesn't depend on the Java side.
When your FileWriter is done writing, and gets closed, the content of that file in your file system has been updated. If that didn't happen for some reason, you some form of IOException should be thrown while running that code.
The question whether your editor that you use to look at the file realizes that the file has changed ... completely depends on your editor.
Some editors will ignore the changes, other editors will tell you "the file changed, do you want to reload it, or ignore the changes".
Meaning: the code you are showing does "synchronously" write that file, there is nothing to do on the "java side of things".
In other words: try using different editors, probably one intended for source code editing, like atom, slickedit, visual studio, ...

How to check whether file is open or not in java [duplicate]

I need to write a custom batch File renamer. I've got the bulk of it done except I can't figure out how to check if a file is already open. I'm just using the java.io.File package and there is a canWrite() method but that doesn't seem to test if the file is in use by another program. Any ideas on how I can make this work?
Using the Apache Commons IO library...
boolean isFileUnlocked = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
isFileUnlocked = true;
} catch (IOException e) {
isFileUnlocked = false;
}
if(isFileUnlocked){
// Do stuff you need to do with a file that is NOT locked.
} else {
// Do stuff you need to do with a file that IS locked
}
(The Q&A is about how to deal with Windows "open file" locks ... not how implement this kind of locking portably.)
This whole issue is fraught with portability issues and race conditions:
You could try to use FileLock, but it is not necessarily supported for your OS and/or filesystem.
It appears that on Windows you may be unable to use FileLock if another application has opened the file in a particular way.
Even if you did manage to use FileLock or something else, you've still got the problem that something may come in and open the file between you testing the file and doing the rename.
A simpler though non-portable solution is to just try the rename (or whatever it is you are trying to do) and diagnose the return value and / or any Java exceptions that arise due to opened files.
Notes:
If you use the Files API instead of the File API you will get more information in the event of a failure.
On systems (e.g. Linux) where you are allowed to rename a locked or open file, you won't get any failure result or exceptions. The operation will just succeed. However, on such systems you generally don't need to worry if a file is already open, since the OS doesn't lock files on open.
// TO CHECK WHETHER A FILE IS OPENED
// OR NOT (not for .txt files)
// the file we want to check
String fileName = "C:\\Text.xlsx";
File file = new File(fileName);
// try to rename the file with the same name
File sameFileName = new File(fileName);
if(file.renameTo(sameFileName)){
// if the file is renamed
System.out.println("file is closed");
}else{
// if the file didnt accept the renaming operation
System.out.println("file is opened");
}
On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using
fileIsLocked = !file.renameTo(file)
most useful, as it avoids false positives when processing write protected (or readonly) files.
org.apache.commons.io.FileUtils.touch(yourFile) doesn't check if your file is open or not. Instead, it changes the timestamp of the file to the current time.
I used IOException and it works just fine:
try
{
String filePath = "C:\sheet.xlsx";
FileWriter fw = new FileWriter(filePath );
}
catch (IOException e)
{
System.out.println("File is open");
}
I don't think you'll ever get a definitive solution for this, the operating system isn't necessarily going to tell you if the file is open or not.
You might get some mileage out of java.nio.channels.FileLock, although the javadoc is loaded with caveats.
Hi I really hope this helps.
I tried all the options before and none really work on Windows. The only think that helped me accomplish this was trying to move the file. Event to the same place under an ATOMIC_MOVE. If the file is being written by another program or Java thread, this definitely will produce an Exception.
try{
Files.move(Paths.get(currentFile.getPath()),
Paths.get(currentFile.getPath()), StandardCopyOption.ATOMIC_MOVE);
// DO YOUR STUFF HERE SINCE IT IS NOT BEING WRITTEN BY ANOTHER PROGRAM
} catch (Exception e){
// DO NOT WRITE THEN SINCE THE FILE IS BEING WRITTEN BY ANOTHER PROGRAM
}
If file is in use FileOutputStream fileOutputStream = new FileOutputStream(file); returns java.io.FileNotFoundException with 'The process cannot access the file because it is being used by another process' in the exception message.

How to delete a file on a method exit in java?

I am trying to figure out how to make sure a temporary file that gets created in a method gets deleted by the time the method returns. I have tried file.deleteOnExit();, but that is for when the program stops, not the method. I have also tried a try and finally block. Is using a finally block the only way to achieve this?
public String example(File file) {
// do some random processing to the file here
file.canWrite();
InputStream() is = new FileInputStread(file);
// when we are ready to return, use the try finally block
try {
return file.getName();
} finally {
is.close();
file.delete();
}
}
I think it looks ugly. Anyone have a suggestion?
As it was mentioned by #BackSlash in your specific case you can just remove file just before return:
file.delete();
return "File processed!";
However in common case if code inside try block can throw exception your approach looks fine. You can also use Aspect Oriented Programming (e.g. using AspectJ) but it looks like overkill in your case.
You can also improve your code by using nice new feature of Java 7. Each instance of Closable will be closed in the end of try block, e.g.:
try (
InputStream in = ...
) {
// read from input stream.
}
// that's it. You do not have to close in. It will be closed automatically since InputStream implements Closable.
So, you can create class AutoDeletableFile that wraps File and implements Closable. The close() method should delete the file. In this code will work exactly as yours:
try (
AutoDeletableFile file = new AutoDeletableFile("myfile.txt");
) {
// deal with file
}
// do nothing here. The file will be deleted automatically since its close() method actually deletes the file.
Well, that's what finally is for.
Of course, in Java7 you can write an AutoCloseable implementation that does the deleting for you and use try-with-resources instead.
If you are using Java 7 you can achieve this by using java.lang.AutoCloseable interface. Details here http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html.
If not then finally is the best and widely used approach for closing/cleaning resources.
Maybe try delete the file at the end of the method (the last line)? This will delete the file right before the method exits if I understand correctly?
File file = new File("file.txt");
file.delete();

How to open a file without saving it to disk

My Question: How do I open a file (in the system default [external] program for the file) without saving the file to disk?
My Situation: I have files in my resources and I want to display those without saving them to disk first. For example, I have an xml file and I want to open it on the user's machine in the default program for reading xml file without saving it to the disk first.
What I have been doing: So far I have just saved the file to a temporary location, but I have no way of knowing when they no longer need the file so I don't know when/if to delete it. Here's my SSCCE code for that (well, it's mostly sscce, except for the resource... You'll have to create that on your own):
package main;
import java.io.*;
public class SOQuestion {
public static void main(String[] args) throws IOException {
new SOQuestion().showTemplate();
}
/** Opens the temporary file */
private void showTemplate() throws IOException {
String tempDir = System.getProperty("java.io.tmpdir") + "\\BONotifier\\";
File parentFile = new File(tempDir);
if (!parentFile.exists()) {
parentFile.mkdirs();
}
File outputFile = new File(parentFile, "template.xml");
InputStream inputStream = getClass().getResourceAsStream("/resources/template.xml");
int size = 4096;
try (OutputStream out = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[size];
int length;
while ((length = inputStream.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
inputStream.close();
}
java.awt.Desktop.getDesktop().open(outputFile);
}
}
Because of this line:
String tempDir = System.getProperty("java.io.tmpdir") + "\\BONotifier\\";
I deduce that you're working on Windows. You can easily make this code multiplatform, you know.
The answer to your question is: no. The Desktop class needs to know where the file is in order to invoke the correct program with a parameter. Note that there is no method in that class accepting an InputStream, which could be a solution.
Anyway, I don't see where the problem is: you create a temporary file, then open it in an editor or whatever. That's fine. In Linux, when the application is exited (normally) all its temporary files are deleted. In Windows, the user will need to trigger the temporary files deletion. However, provided you don't have security constraints, I can't understand where the problem is. After all, temporary files are the operating system's concern.
Depending on how portable your application needs to be, there might be no "one fits all" solution to your problem. However, you can help yourself a bit:
At least under Linux, you can use a pipe (|) to direct the output of one program to the input of another. A simple example for that (using the gedit text editor) might be:
echo "hello world" | gedit
This will (for gedit) open up a new editor window and show the contents "hello world" in a new, unsaved document.
The problem with the above is, that this might not be a platform-independent solution. It will work for Linux and probably OS X, but I don't have a Windows installation here to test it.
Also, you'd need to find out the default editor by yourself. This older question and it's linked article give some ideas on how this might work.
I don't understand your question very well. I can see only two possibilities to your question.
Open an existing file, and you wish to operate on its stream but do not want to save any modifications.
Create a file, so that you could use file i/o to operate on the file stream, but you don't wish to save the stream to file.
In either case, your main motivation is to exploit file i/o existingly available to your discretion and programming pleasure, am I correct?
I have feeling that the question is not that simple and this my answer is probably not the answer you seek. However, if my understanding of the question does coincide with your question ...
If you wish to use Stream io, instead of using FileOutputStream or FileInputStream which are consequent to your opening a File object, why not use non-File InputStream or OutputStream? Your file i/o utilities will finally boil down to manipulating i/o streams anyway.
http://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html
http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html
No need to involve temp files.

Categories

Resources