I'm new to java, and I'm trying to get a Java program to create a .html file, put some code in it, then run it. So far I can get it to create the file and it runs correctly, but is there a way to have the Java program automatically run the .html file or must it be done manually?
So, it really depends on on what do you mean by "Running it", you can either:
Create a webview and load in the file
Or you can make the default browser load in the file and display it like so:
try {
Runtime.getRuntime().exec("cmd.exe /c start c:/path/to/html/file");
} catch (IOException e) {
e.printStackTrace(); // if something goes wrong
}
In my java code, I am using renameTo method to rename the file. I am able to do it successfully if the file is closed physically. But I am unable to do so if the file I am trying to rename is open.
How do I close the file thru code?
This is the code :
File file = new File("/users/abc.txt");
File newFile = new File("/users/xyz.txt");
if (file.renameTo(newFile)) {
System.out.println("File rename success");
} else {
System.out.println("File rename failed");
}
Thanks in advance.
You cannot close a file in Java that is opened by another user. It is highly platform dependant, it is impossible if that user/process has higher priviledges then your process, and the user editing it might hava data loss, if he is in the process of editing that file in an Editor. Don't ever do that.
The only way would be to wait until the file has been closed by that other user like that, however, I still discourage from doing so. If you have to use that file, just exit your application with an error.
File file = new File("/users/abc.txt");
File newFile = new File("/users/xyz.txt");
try {
while (!file.renameTo(newFile)) {
Thread.sleep(10_000); // wait 10 seconds
}
} catch (InterruptedException ex) {
// ignore
}
I know that this question it is similar to this one but it is different. I am trying to open a pdf file that it is in the resources folder of netbeans.
Right now I am in the EventoService.java and I have created a file object to open the pdf file (justificante.pdf) in "Other Resources" folder. I have tried to reach the pdf file like in the link before but it doesn't work because of the constructor. How can I reach it? Thank you in advance.
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File(getClass().getClassLoader().getResource("resources/justificante.pdf"));
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}
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.
Using Java program I need to run/open/edit any file. This should have similar effect of double clicking file in File Explorer and OS will execute file if it an executable OR open/edit it in it's respective registered program.
I have tried the Runtime.exec() method (See down there) but that method only runs executable files. I need mine to run any file. This includes text files, audio files, pictures, anything.
I have tried the following:
Runtime.getRuntime().exec("README.txt");
Have you consider trying to use the java.awt.Desktop class?
For example...
if (Desktop.isDesktopSupported()) {
try {
if (Desktop.getDesktop().isSupported(Desktop.Action.EDIT)) {
Desktop.getDesktop().edit(new File("Readme.txt"));
}
// or...
if (Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
Desktop.getDesktop().open(new File("Readme.txt"));
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
This will attempt to open/edit the file in the OS specified editor for the given file