Deleting file inside JComboBox - java

I've got a JComboBox filled with some java.io.File objects. By selecting one of these files in the ComboBox, I want to delete it either from the ComboBox and Filesystem.
Code snippet:
deleteButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(null, "Are you sure?", "Warning", dialogButton);
if (dialogResult == JOptionPane.YES_OPTION)
{
Path path = Paths.get(mailingLists.getSelectedItem().toString());
mailingLists.removeItem(mailingLists.getSelectedItem());
try
{
Files.delete(path);
JOptionPane.showMessageDialog(null, "File deleted!", "SUCCESS", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e1)
{
JOptionPane.showMessageDialog(null, e1.toString(), "ERROR", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
}
}
});
It gives this exception: java.nio.file.FileSystemException [...] file already in use this is because it's used by my application, then I thought first to remove it from the ComboBox and then delete it using Files.delete(path); but still have the exception.
What's wrong?
P.S.
Is the first time that I deal in this context so I guess if it's better to use File f = new File("path"); f.delete(); instead of Files.delete(path);.
EDIT: Provided more information about the JComboBox load.
Scratch:
LinkedList<File> listFolder = new LinkedList<File>();
listFolder.add(new File("mailinglists"));//<--- root folder
File[] stuffInFolder = listFolder.get(0).listFiles();
JComboBox<File> mailingLists = new JComboBox<File>(stuffInFolder);

Sounds like you need to close the file.
When you open a file the OS will prevent a file from being deleted until the connection to the file has been closed.

I would recommend, instead of JComboBox filled with some java.io.File objects use file names with path as String. And when you have to delete the file create an Object of File using the path and delete it.

Use Java.io.File.delete()
try
{
File f = new File(path);
if(f.delete())
JOptionPane.showMessageDialog(null, "File Deleted Succesfully!");
else
JOptionPane.showMessageDialog(null, "File couldn't be deleted!");
}

Solved!
I was using a "bugged" external library developed by a workmate. Its goal was to read a .properties file. Once readed, the file was still opened.
Fixed and everything works well now.

Related

How to read text and font from .doc using Aspose Word for Java

I have an assignment to read and write to a .doc file and must be able to read the font setting for each word. I'm currently using Aspose word for Java in my development, the write to word and including the font setting to each word is running. The only problem is sometimes when i try to pick a .doc file and read it using the code below, it returns nothing from the System.out.print. But also sometimes it came but with only few words rather than the whole content.
final JFileChooser fc = new JFileChooser();
HomeForm form = new HomeForm();
if (evt.getSource() == jButton2)
{
int returnVal = fc.showOpenDialog(HomeForm.this);
File file = fc.getSelectedFile();
if (returnVal == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, "File " +file.getName()+" choosed", "Alert", JOptionPane.CLOSED_OPTION);
jTextField1.setText(file.getName());
String dataDir = file.getPath();
String filename = file.getName();
try {
InputStream in = new FileInputStream(dataDir);
Document doc = new Document(in);
System.out.println(file.getName());;
System.out.println(doc.getText());
in.close();FileInputStream(file.getAbsolutePath());Logger.getLogger(HomeForm.class.getName()).log(Level.SEVERE, null, ex);InputStreamReader(fis, Charset.forName("UTF-8"));
} catch (FileNotFoundException ex) {
Logger.getLogger(HomeForm.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(HomeForm.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
JOptionPane.showMessageDialog(null, "File choose canceled", "Alert", JOptionPane.CLOSED_OPTION);
}
}
Am i heading toward a right direction by using this code for reading each word and each word font setting? Or maybe Aspose can't handle these kind of processings? Please help, thank you for your time.
You can use Aspose.Words for Java API to get text and Font name of each Run in Document by using the following code:
Document doc = new Document("D:\temp\in.doc");
for(Run run : (Iterable) doc.getChildNodes(NodeType.RUN, true)) {
System.out.println(run.getText());
System.out.println(run.getFont().getName());
}
I work with Aspose as Developer Evangelist.

Java: open text file as html file with browser using File.renameTo()

I want to convert a text file to a html file and then open it with a browser. I try to use file.renameTo() to rename the text file's extension to .html but the rename attempt always fails and file.renameTo() always returns false. Therefore, when I try to open the file in the below method, the file is opened in notepad.
file declaration:
private File file;
file declaration in constructor:
file = new File("D:/dc1000/Project/webPage.txt");
file.getParentFile().mkdirs();
method that doesn't work:
public void compileWebpage(){
File file2 = new File("D:/dc1000/Project/CompiledWebpage.html");
file2.getParentFile().mkdirs();
addFileTags("end"); //add ending tags like </body>
boolean success = true;
try{
success = file.renameTo(file2);
}catch (Exception e){
System.out.println(e);
}
if(!success){
System.out.println("webPage compilation failed.");
}
Desktop desktop = Desktop.getDesktop();
try{
desktop.browse(file.toURI());
}catch (IOException e){
e.printStackTrace();
}
}
No exceptions are thrown, "Webpage compilation failed" is printed to the console and then notepad opens the file. The file looks like this when opened in notepad:
<html>
<head>
</head>
<body>
<p>hi</p>
</body>
</html>
Why does File.renameTo() always fail? How can I open this text file in a browser as a html file?
Well, off hand it's rather hard to tell without truly knowing what the addFileTag() method is doing. The only reason I can think of is that the webPage.txt file is still open for either read or write operations.
Your code has accessed the file but never closed it again. You can't rename a file that is open. I would have to assume this is in fact done somewhere within the addFileTag() method.
Because your call to the File.renameTo() method was unsuccessful the "webPage.txt" text file was never renamed to "CompiledWebpage.html" so in essence the "CompiledWebpage.html" file simply does not exist within the system. This however is not the reason why the Windows NotePad application is opening your file instead of the expected default Web Browser:
To begin with the File object variable so conveniently named 'file' was declared and initialized to be related to the "D:/dc1000/Project/webPage.txt" text file and it always will be since it's Class global unless of course that relationship is changed somewhere within your code. To be blunt... it's not and I guess it's a good thing for now because IF your File Rename was successful you would have simply gotten an FileNotFound Exception because the text file related to the 'file' variable would no longer exist due to the simple fact that it was renamed.
What you really want to pass to the DeskTop.browse() method is the File object 'file2' variable which is related to the "D:/dc1000/Project/CompiledWebpage.html" text file. Mind you, you'll still get an FileNotFound Exception because the File.renameTo() method had failed. So you definitely want to make sure you have success here.
Whatever...Why did the Windows NotePad application open instead of the Web Browser?
Here's why:
The Operating System File Associations is what determines which application will open the file when using the DeskTop.browse() method. In the Windows Operating System, by default, a file with the file name extension of ".txt" is automatically opened and displayed within NotePad, a file with the file name extension of ".docx" is automatically opened and displayed in MS Office WORD, a file with the file name extension of ".html" is opened and displayed within the default Web Browser. I think you get the idea here.
Because the 'file' variable is still related to the file "D:/dc1000/Project/webPage.txt" and because the File.renameTo() method failed, Windows simply seen the .txt file extension and displayed the file (as stipulated within the 'file' variable) to NotePad.
So...How do I get all this to actually Work!?
Well, if I may be so bold, do this instead:
Place this somewhere in your code, a button action event or whatever:
String sourceFile = "D:/dc1000/Project/webPage.txt";
String destinationFile = "D:/dc1000/Project/CompiledWebpage.html";
boolean success = CompileToWebPage(sourceFile, destinationFile, "This is My Head Text");
if (success) {
System.out.println("Text File Successfully Compiled!");
}
else {
System.out.println("Text File Compilation FAILED!");
}
//Display our new file in the web Browser...
try {
File htmlFile = new File(destinationFile);
Desktop.getDesktop().browse(htmlFile.toURI());
} catch (IOException ex) {}
Here is a new CompileToWebPage() method:
private static boolean CompileToWebPage(final String sourcefilePath,
final String destinationFilePath, String... headText) {
// headText is OPTIONAL.
String headTxt = "";
if (headText.length != 0) { headTxt = headText[0]; }
//Read sourcefilePath file data into a String ArrayList...
BufferedReader input;
try {
input = new BufferedReader(new FileReader(sourcefilePath));
if (!input.ready()) { throw new IOException(); }
}
catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\nThe supplied "
+ "file path was not found!\n\n" + sourcefilePath, "File NotFound",
JOptionPane.ERROR_MESSAGE);
return false;
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\nThe supplied "
+ "file is not ready to be read!\n\n" + ex.getMessage(), "File Not Ready",
JOptionPane.ERROR_MESSAGE);
return false;
}
// Place required HTML Tags into String ArrayList
ArrayList<String> txt = new ArrayList<>();
txt.add("<html>");
txt.add("<head>");
txt.add(headTxt);
txt.add("</head>");
txt.add("<body>");
// Read each line of the source text File and add
// them to our String ArrayList...
try {
String str;
while((str = input.readLine()) != null){
txt.add("<p>" + str + "</p>");
}
input.close();
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\n"
+ "There was a problem reading the source Text from file!\n\n"
+ ex.getMessage(), "File Read Error", JOptionPane.ERROR_MESSAGE);
return false;
}
// Place our HTML finishing Tags into our String ArrayList...
txt.add("</body>");
txt.add("</html>");
// Write the String ArrayList to our supplied Destination
// File Path...
try {
FileWriter fw = new FileWriter(destinationFilePath);
Writer output = new BufferedWriter(fw);
for (int i = 0; i < txt.size(); i++) {
// Some Windows applications (such as NotePad require
// the \r tag for a new line to actually be accomplished
// within a text file.
output.write(txt.get(i) + "\r\n");
}
output.close();
return true;
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\n"
+ "There was a problem writing the Compiled Web Text to file!\n"
+ "Ensure that permissions are properly set.\n\n" + ex.getMessage(),
"File Write Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
Well, I hope this has helped you somewhat or at the very least been entertaining.

Java FileNotFoundExeception not working

In my current project I am having an issue with not receiving a file not found exception. My driver file passes the path to be opened to the constructor that is building a library of books. I am using JFileChooser to get the path. In trying to force an error (entering the name of a file that does not exist), it builds the library with no information in it, and does not throw an error.
Driver Code:
//open an existing library
JFileChooser dlg = new JFileChooser ("LibraryData");
FileNameExtensionFilter filter = new FileNameExtensionFilter ("Text Files", "txt");
dlg.setFileFilter(filter);
dlg.setDialogTitle("Select Existing File");
dlg.setApproveButtonToolTipText("Select the file you want to open and click me.");
int button = dlg.showOpenDialog(null);
if (button == dlg.APPROVE_OPTION)
{
currentPath = dlg.getSelectedFile().getPath();
library = new PersonalLibrary(currentPath);
System.out.println("===========================================================");
System.out.println("File opened successfully from: \n" + currentPath);
System.out.println("===========================================================");
}
Util.enterToContinue();
Util.clearScreen();
break;
Library Code:
public PersonalLibrary(String path)
{
try
{
File myFile = new File(path);
if (myFile.exists())
{
Scanner input = new Scanner(myFile);
while(input.hasNext())
{
//code that populates the library
}
input.close();
saveNeeded = false;
}
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
Your checking if the file exists the catch block will never be executed.
if(myFile.exists())
If it doesn't exist nothing else will be executed including catch block. FileNotFoundException could not occur in this block of code. If you want to catch FileNotFoundException get rid of the if block. Or just add an else block and do you processing there whatever processing you want to do when a file doesn't exist.
the method File#exists() checks if a file is existing or not. If it does, it returns true and goes into your if block.
Since the file is not there, it just simply skips the if block and moves on. Since no attempt was made to access a non-existing file object, the exception is not thrown.
If you would like to throw an exception, you have to do so yourself like this,
if(file.exists()) {
//do file operation
} else {
throw new FileNotFoundException("Oops! No file...");
}

JFileChooser / FileWriter doesn't let me save in root of C: disk

I'm playing around and I made a notepad-like app using swing. Everything is working properly so far, except it's not letting me save the text file directly on C:/. On any other disk, and INCLUDING the root of the D: drive, or in folders of the C:/ disk it works like a charm. Why is this happening?
This is my code:
file_save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser Chooser = new JFileChooser();
File DefaultDirectory = new File("C:/");
File Path;
int Checker;
FileFilter text_filter = new FileNameExtensionFilter(
"Text File (*txt)", "txt");
FileFilter another_filter = new FileNameExtensionFilter(
"Debug Filter (*boyan)", "boyan");
//
Chooser.setCurrentDirectory(DefaultDirectory);
Chooser.setDialogTitle("Save a file");
Chooser.addChoosableFileFilter(text_filter);
Chooser.addChoosableFileFilter(another_filter);
Chooser.setFileFilter(text_filter);
Checker = Chooser.showSaveDialog(null);
//
if (Checker == JFileChooser.APPROVE_OPTION) {
Path = Chooser.getSelectedFile();
System.out.println(Path.getAbsolutePath());
;// Just for
// debugging.
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(Path
.getAbsolutePath()));
String[] myString = textArea.getText().split("\\n");
for (int i = 0; i < textArea.getLineCount(); i++) {
writer.append(myString[i]);
writer.newLine(); // SO IT CAN PRESERVE NEW LINES
// (APPEND AND SPLIT ARE ALSO
// THERE
// BECAUSE OF THAT)
writer.flush();
}
JOptionPane.showMessageDialog(null, "File saved.", "",
JOptionPane.WARNING_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
}
}
}
}
});
Thanks a lot in advance!
Usually, one does not have write permissions in C:\.
Start the app as a privileged user
One should not do that, as it is not intended by OS design. Changing permissions on C:\, or the system drive respectively, is a no-go.
Save into a sub-directory of System.getProperty("user.home"); (way to go)
The user home could also be a network folder with nighly backup in a domain network, for example. Especially for remote sessions (RDP, Citrix), this is often the case.
If you absolutely need to install a static file outside of the users folders, do it once, with an installer, configured to raise privileges (UAC).

Replacing the Host file in Java

So here's my code so far, yes I know it's pretty basic. But what I would Like to accomplish is to Replace the host file located in the System32\drivers\etc folder, the problem I am having in doing this is that I am getting an access denied error. How can I give the program access to make changes within the windows folder, also the class SaveURL just downloads the file and uses two strings to pass the name and download location through the function saveImage. How can I give myself access? Thanks in advance I truly appreciate it.
private void jButton7MouseClicked(java.awt.event.MouseEvent evt) {
String destinationHosts = "hosts";
String urlHosts = "https://dl.dropbox.com/s/awdvoprxyo7r2q6/hosts?dl=1";
Object hostOptions[] = {"Replace", "Close"};
File fileHosts = new File(destinationHosts);
File dirHost = new File("hosts");
boolean dirHosts = dirHost.mkdir();
try {
Runtime.getRuntime().exec("notepad.exe \\Windows\\system32\\drivers\\etc\\hosts");
jTextArea2.append("Opening Host File \n");
int hostFile = JOptionPane.showOptionDialog(rootPane, "Would you like to replace the Hosts File?",
"Yes or No", JOptionPane.YES_NO_OPTION, JOptionPane.NO_OPTION, null, hostOptions, hostOptions[0]);
if (hostFile == JOptionPane.YES_NO_OPTION) {
jTextArea2.append("Downloading New Host File");
SaveUrl.saveImage(urlHosts, destinationHosts);
fileHosts.renameTo(new File(dirHost, fileHosts.getName()));
Path source = Paths.get("\\hosts\\hosts");
Path target = Paths.get("\\Windows\\system32\\drivers\\etc\\");
Files.copy(source, target);
jTextArea2.append("Host file replaced");
}
} catch (IOException ex) {
Logger.getLogger(ToolKit1.class.getName()).log(Level.SEVERE, null, ex);
}
}

Categories