Not able to delete the file001.txt which is created in my local dir path by using the removeFile(s) method in switch case. Then the method removeFile(s) calls the class Employee_Remove, where file.delete() method does not delete the files. Please find the below 2 codes and also screenshot.
I don't want to create duplicate or renaming the filename. I just need to delete the files which is created in my local dir. I did not understanding the problem whether it code problem or Eclipse problem.
Can anyone help to solve the issue.
case 3:
{
System.out.print("\nPlease Enter Employee's ID :");
String s=sc.nextLine();
Employee_Remove epr =new Employee_Remove();
epr.removeFile(s);
break;
}
class Employee_Remove {
public void removeFile(String ID) {
File file = new File("file" + ID + ".txt");
if (file.exists()) {
if (file.delete()) {
System.out.println("\nEmployee has been removed Successfully");
}
} else {
System.out.println("\nEmployee does not exists :( ");
}
}
}
If you get no output to the Eclipse console window, that means that:
Your application code has found the file. If it didn't find it, you would get a message.
The file was not deleted. If the delete had succeeded, then you would get a message to say so.
It is not clear why your application found the file but did not delete it deleted. One possibility is that your application does not have permission to delete the file. A second possibility is that something else has the file open. On Windows that locks the file, and that would prevent the application from deleting it. (There are some other more obscure causes, but I doubt that they would be applicable here ...)
If you want to get diagnostics that explain give more information about why the file wasn't deleted, switch to using the newer java.nio.file.* APIs; e.g. java.nio.file.Files::delete(Path).
If the output is NOT as you described, then it is possible that the application DID delete the file (and said so) but Eclipse has not noticed. In my experience Eclipse does not notice changes made to files that were not made by Eclipse itself.
If this is the case, then doing an Eclipse refresh should update the view. The Eclipse shortcut for this is typically F5 or CNTRL-F5, but check the key bindings.
Related
I want to set up only one instance of the CHM file when clicking on "Help" in the menubar and stopping it from opening twice when clicked again - therefore how do I code it?
I've tried to use it with process.isAlive(), but after I close it I want a counter set to zero, which only opens another CHM file when the counter is 0.
helpMenu.addMouseListener(new MouseAdapter() {
// do this after clicked
openCHM();
});
So MouseEvent is fired once.
openCHM() {
Process p;
if(cnt == 0) {
p = Runtime.getRuntime().exec("hh.exe Help.chm");
cnt++;
if(!p.isAlive()) {
cnt = 0;
}
}
I expected the counter to be 0, but then came to the conclusion that MouseEvent already fired once and the code got already executed, therefore it never goes to the second if-statement and sets my counter to 0.
EDIT
There is no correct answer how to open a CHM file once, but there is a workaround that makes it possible, we just need to look if the file is renamable or not.
protected void openCHM() {
try {
File file = new File("YOURNAME.chm");
boolean renamable = file.renameTo(file); // can't rename if file is already open, returns true if renaming is possible
if(renamable) {
Runtime.getRuntime().exec("hh.exe YOURNAME.chm");
} else if(!file.exists() ){
// message: file doesn't exist (in path)
} else {
// file is already open
}
} catch () {
}
}
I'm not a Java programmer but the short story - not possible (AFAIK).
You know, hh.exe is the HTMLHelp executable and associated with *.CHM files. It's just a shell that uses the HTML Help API and is really just hosting a browser window.
HH.EXE is not single instance, if you open a CHM or another file three times using HH.EXE, then three help windows will appear. Try it using PowerShell:
PS D:\_working> hh.exe C:\Windows\Help\htmlhelp.chm
Several client-side command line switches are available to help authors that are part of the HTML Help executable program (hh.exe) and therefore work when HTML Help Workshop is not set up.
KeyHH.exe was running years ago with special parameters.
If you call the HH API directly from your application, and not via a second helper program like HH.EXE or KEYHH.EXE, then you MUST close any open help windows before shutting down the application or you will probably crash Windows.
For some information related to the problem you maybe interested in Open CHM File Once.
Some quoted info from the link above:
When you do that you are just calling the help viewer again and again from the command line, you're not using the HTML Help API which is what you need to access the CHM once it is open. You need to check whether your flavors of Java and Smalltalk support calls to the HTML Help API. This API is documented in detail in the help file of Microsoft HTML Help Workshop, which is the compiler package you installed to be able to generate CHMs.
I have a requirement of implementing a Watch Service on a folder. This is straight forward approach of using Java7's watch service. I have successfully done it, I am able to capture events whenever a file is created/updated/deleted on the folder where I have been watching. The problem here is it is not applicable for contents of sub folders and it is clearly written in the documentation. My requirement is to watch over contents of sub folder as well. This is not possible using the above approach unless I write a loop over all the sub folders manually and listen to each and every folder, this I think leads to some memory leak if not programmed well. Hence I am going with what spring suggested in the newer release explained here This is very clear approach which I have seen for WatchService. The problem here is this will listen to only ENTRY_CREATE events i.e., only the events where we have created the file and this can be at any level. This is not working when I change the file or delete the file. How should we go ahead in this case.
public static void watchFolderTree(String pathStr)
throws Exception
{
long waitTime = 10000;
WatchServiceDirectoryScanner scanner = new WatchServiceDirectoryScanner(pathStr);
scanner.start();
List<File> changedFiles = null;
while(true)
{
changedFiles = scanner.listFiles(new File(pathStr));
if(changedFiles.size() > 0)
{
System.out.println("There is a file ");
}
Thread.sleep(waitTime);
}
}
References :
Monitor subfolders with a Java watch service
JAVA 7 watch service
I am having an issue with a panel i am working on, what I am working on is whenever there is an upgrade from one version of the software to another the older start menu group on the windows machine still shows. I have tried to see if i can delete the old directory first and then make the new one but all that happens is the old one is still staying. Not really sure how to go about it all I need is just one directory in the start menu group to show weather I delete or rename the old.
Here is what I have so far to delete the old system variable. This is something I am working on and i know its not perfect but any help would be appreciated. If you need explanations I would be happy to comply. Thank you
if ( PrioGlobals.UPGRADE ){
oldm_txtGrpName.setText(PrioGlobals.StartMenuFolder);
}
if ( PrioGlobals.UPGRADE ){
String oldShortCutPath = PrioGlobals.cre.getShorcutDirectory();
String oldStartMenuGroupFolderPath = oldShortCutPath + File.separator + BrandStrings.WIN_FOLDER_NAME +
File.separator +oldm_txtGrpName.getText();
File oldStartmenu = new File(oldStartMenuGroupFolderPath);
if (oldStartmenu.exists())
{
oldStartmenu.delete();
}
else
oldStartmenu.delete();
}
If I am reading your code correctly, oldStartmenu is a directory? In that case, oldStartmenu.delete() will probably fail because the directory is not empty (see File delete) In which case you need to delete the directory and all of it's files recursively.
At which point I would recommend including commons-io FileUtils and use one of the directory utilities such as forceDelete or deleteDirectory
[update]
Once you have added the commons-io library to your project you would
// import FileUtils
import org.apache.commons.io.FileUtils;
// ...
if (oldStartmenu.exists())
{
FileUtils.deleteDirectory(oldStartmenu);
}
I have a series of folders containing books on a server which I am accessing with this piece of code. I want to make each of these folders an object so I can do some work with the files inside them later on. I'm trying to use this method to return a list of the folders as Book objects.
public List<Book> getBooks(File folder){
List<Book> books = new ArrayList<Book>();
for (File f : folder.listFiles()){
if (f.isDirectory()){
System.out.println(f.getAbsolutePath() + "" + f.listFiles());
books.add(new Book(f));
}
}
return books;
}
The println statement in this block is printing, as it should, the direct path to the folder and then the memory address along with some other information. However, somewhere in the folder it is printing out null when listFiles() is called. The folder that it is doing this on is not empty. This supposedly empty folder is then passed to my class init method.
public Book(File bookFolder) {
this.bookFolder = bookFolder;
this.bookPath = bookFolder.getAbsolutePath();
System.out.println(bookFolder + " " + bookFolder.listFiles());
for (File f : bookFolder.listFiles()) {
...
}
}
The println statement in this block prints out the exact same path to the folder and then a different memory address, which is also expected. When it hits the "empty" folder it prints null for the memory address again.
Now, for the real issue, the line with the for loop is where the program crashes and throws a NullPointerException which isn't even described in the documentation for the listFiles method.
Why could this be happening? Also, why are my non-empty folders returning null?
The documentation for the listFiles() method clearly states that it "Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs."
One of the most common reasons that a directory cannot be listed is that the process lacks the right permissions. Are you running this as yourself, or in some sort of service that runs as a different user?
By the way, the File API is a great example of how bad life can be without exceptions.
For developers who have already included the following solutions :
Added the storage permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2.The directory from you want to list the files exists.
Enabled the permission in the device you are testing in the app permission settings
BELOW CODE WILL SOLVE YOUR PROBLEM IF YOUR DEVICE SDK IS GREATER THAN OR EQUALS TO ANDROID 10(Q)
In the manifest file include this code inside tag
<application android:requestLegacyExternalStorage="true"...</application>
Let me know if your problem is solved!
I had a similar problem with dir.listfiles(); returning null for the user folder \AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\
it was the folder had by default Permissions set on "everyone" Deny all
what screwed me over i think was the fact that I never expected any Deny permission to exist there.
also for any one thats unclear on what i mean by a deny permission
when you set deny for user permissions it overrides the allow for user permissions unless you remove it and it was on a default install of windows 10 home.
For me it was caused by trailing spaces. Use variable.trim()
I'm developing an editor plugin for eclipse. It works fine on files within eclipse projects, but when an external file is opened via the "File -> Open File" menu (which works file with, e.g. Java files), I get a page displaying nothing but a horizontal blue line and the word "ERROR". The Error Log of eclipse is empty, as is the log file in the .metadata directory.
What could cause this? How can I diagnose the error when I have no error message that tells me where to look? There doesn't seem to be a way to get more detailed logging from eclipse.
Edit:
I've found that the source of the problem is close to what jamesh mentioned, but not a ClassCastException - there simply is no IDocument instance for the text viewer to display because StorageDocumentProvider.createDocument() returns null. The reason for this is that it only knows how to create documents for instances of org.eclipse.ui.IStorageEditorInput, but in this case it gets an instance of org.eclipse.ui.ide.FileStoreEditorInput, which does not implement that interface, but instead implements org.eclipse.ui.IURIEditorInput
I had the same probleam and finally found solution working for me.
You have to provide 2 different document providers - first extending FileDocumentProvider for files inside your workbench, and second extending TextFileDocumentProvider for other resources outside your workspace. Then you register the right provider acording to the input in your editors doSetInput method like this:
private IDocumentProvider createDocumentProvider(IEditorInput input) {
if(input instanceof IFileEditorInput){
return new XMLTextDocumentProvider();
} else if(input instanceof IStorageEditorInput){
return new XMLFileDocumentProvider();
} else {
return new XMLTextDocumentProvider();
}
}
#Override
protected final void doSetInput(IEditorInput input) throws CoreException {
setDocumentProvider(createDocumentProvider(input));
super.doSetInput(input);
}
then in your new document provider (extending TextFileDocumentProvider) insert somethnig like this:
protected FileInfo createFileInfo(Object element) throws CoreException {
FileInfo info = super.createFileInfo(element);
if(info==null){
info = createEmptyFileInfo();
}
IDocument document = info.fTextFileBuffer.getDocument();
if (document != null) {
/* register your partitioner and other things here
same way as in your fisrt document provider */
}
return info;
}
This works for me :) Finally I have to mention, that I'm not so clever and that I copied this solution from project Amateras (Opensource HTML editor plugin for eclipse)
I'm a little away from the source code at the moment, though I suspect the problem is a ClassCastException:
For a workspace file, the IEditorInput is org.eclipse.ui.IFileEditorInput.
For a local non-workspace file, the IEditorInput is org.eclipse.ui.IStorageEditorInput
The difference is in how you get the contents from the IEditorInput. The JDT does an explicit instanceof check to make the switch.
I don't think that the getAdapter(Class clazz) will return a java.io.InputStream if you offer it.
I don't quite understand why they do it like this, but it feels ugly.
Edit:
A more general point about debugging eclipse apps - it's really very useful to try and assemble all your logs into one place (i.e. the console).
To do this, make sure you use the command line options -console and -consoleLog. The latter has helped save countless hours of time. If you haven't already, learn the most basic things about how to use the console (ss and start are my most often used). This will save some more time diagnosing a certain class of problem.
Did you try creating a JAVA file using the editor, outside the workspace?
When calling the editor with the file path, concat "file://" at the beginning of the file path.e.g: if the path is C://temp//Sample.java, then modify it as file://C://temp//Sample.java.