search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
1. Understand the Eclipse resource change monitoring mechanism
2. Implement “dirty” file detection
3. Manage the "dirty" and "saved" status of files
4. Precautions and best practices
Summarize
Home Java javaTutorial Java Eclipse plug-in development: detecting and tracking 'dirty' files in projects

Java Eclipse plug-in development: detecting and tracking 'dirty' files in projects

Jan 01, 2026 am 10:33 AM

Java Eclipse plug-in development: detecting and tracking

In Eclipse plug-in development, a common requirement is to know in real time which files have been modified in the project, that is, they are in a "dirty" state (the file content has been changed but has not been saved). These files are usually marked with an asterisk (*) next to the file name in the IDE. This article will introduce in detail how to implement this function through Eclipse's resource listening mechanism, and provide a practical code example and related precautions.

1. Understand the Eclipse resource change monitoring mechanism

The Eclipse workspace (Workspace) provides a powerful resource change monitoring mechanism, allowing plug-in developers to be notified when files, folders or projects are created, modified, deleted and other operations. The core interface is IResourceChangeListener, which is registered to the workspace through the ResourcesPlugin.getWorkspace().addResourceChangeListener() method.

When a resource changes, the resourceChanged method is called and an IResourceChangeEvent object is passed in. This event object contains detailed information about the change. In particular, IResourceDelta can be obtained through the event.getDelta() method. It is a tree structure of resource changes that describes the changes to all resources since the last event.

2. Implement “dirty” file detection

To detect modifications to file content, we need to pay attention to events of type IResourceChangeEvent.POST_CHANGE, because these events are triggered after the workspace change is completed, providing the complete change difference (delta). Then, we need to traverse IResourceDelta and find those resources whose type is IResourceDelta.CHANGED and whose flag bit contains IResourceDelta.CONTENT.

The following is a sample code that implements file content modification detection:

 import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;

import java.util.Set;
import java.util.HashSet;

public class DirtyFileTracker {

    // Assume there is a Logger, here it is simplified to System.err
    private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(DirtyFileTracker.class.getName());

    // A collection used to store the current "dirty" files private Set<iresource> dirtyFiles = new HashSet();

    public DirtyFileTracker() {
        //Register the resource change listener ResourcesPlugin.getWorkspace().addResourceChangeListener(
            new IResourceChangeListener() {
                @Override
                public void resourceChanged(final IResourceChangeEvent event) {
                    // Only process the POST_CHANGE event to ensure that all changes have been completed if (event.getType() != IResourceChangeEvent.POST_CHANGE) {
                        return;
                    }

                    IResourceDelta delta = event.getDelta();
                    if (delta == null) {
                        return;
                    }

                    IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() {
                        @Override
                        public boolean visit(IResourceDelta delta) throws CoreException {
                            IResource res = delta.getResource();

                            // Only process file resources if (res.getType() != IResource.FILE) {
                                return true; // Continue to access child nodes}

                            switch (delta.getKind()) {
                                case IResourceDelta.CHANGED:
                                    // Check whether the file content has changed if ((delta.getFlags() &amp; IResourceDelta.CONTENT) != 0) {
                                        //The file content has been modified, add it to the dirty file list addDirtyFile(res);
                                        LOGGER.info("The file content has been modified: " res.getFullPath());
                                    }
                                    // Check if the file has been saved (for example, via an editor save operation)
                                    // Note: It is complicated to directly determine whether a file is "no longer dirty" through IResourceDelta // Usually it needs to be combined with other mechanisms, such as editor life cycle events // The logic here is that if the file content changes, it is marked as dirty break;
                                case IResourceDelta.REMOVED:
                                    //The file is deleted and removed from the dirty file list removeDirtyFile(res);
                                    LOGGER.info("File deleted: " res.getFullPath());
                                    break;
                                // Other types of changes can be handled as needed, such as ADDED
                                case IResourceDelta.ADDED:
                                    // Add a new file. If it is subsequently modified, IResourceDelta.CONTENT will capture break;
                                default:
                                    break;
                            }
                            return true; // Continue to access child nodes}
                    };

                    try {
                        delta.accept(visitor);
                    } catch (CoreException e) {
                        LOGGER.severe("An error occurred while traversing IResourceDelta: " e.getMessage());
                    }
                }
            }, IResourceChangeEvent.POST_CHANGE // Listen for POST_CHANGE event);
    }

    /**
     * Add the file to the dirty file list* @param file dirty file*/
    private synchronized void addDirtyFile(IResource file) {
        dirtyFiles.add(file);
    }

    /**
     * Remove the file from the dirty file list* @param file Saved or deleted file*/
    public synchronized void removeDirtyFile(IResource file) {
        dirtyFiles.remove(file);
    }

    /**
     * Get the list of all current "dirty" files * @return a copy of the dirty file collection */
    public synchronized Set<iresource> getDirtyFiles() {
        return new HashSet(dirtyFiles);
    }

    // The listener can be removed when the plug-in is stopped public void dispose() {
        ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
    }

    // Example usage public static void main(String[] args) throws InterruptedException {
        // In the actual plug-in, DirtyFileTracker will be instantiated when the plug-in starts tracker = new DirtyFileTracker();
        System.out.println("DirtyFileTracker has been started, monitoring file changes...");

        // Simulate some operations and wait for changes to occur // In a real Eclipse environment, you need to manually modify and save the file to trigger the event Thread.sleep(60000); // Wait for one minute to observe the effect System.out.println("Current dirty file list:");
        for (IResource res : tracker.getDirtyFiles()) {
            System.out.println(" - " res.getFullPath());
        }

        tracker.dispose(); // Clean up when the plugin is closed}
}</iresource></iresource>

3. Manage the "dirty" and "saved" status of files

The above code snippet is mainly responsible for detecting modifications to the file content and marking it as "dirty". However, when the user clicks "Save" or uses a shortcut key to save the file, the file will no longer be "dirty". IResourceDelta itself does not directly indicate when a file changes from "dirty" status to "saved" status.

To fully track file status, you need to:

  1. Maintain a custom collection of "dirty" files : dirtyFiles Set in the example. Files are added to this collection when the IResourceDelta.CONTENT flag is detected.
  2. Listening for save operations : This is usually more complex than detecting it directly via IResourceDelta. A common approach is to listen to the lifecycle events of the editor (IEditorPart), specifically when the editor is saved (for example, after returning false via IEditorPart.isDirty()).
    • You can register IPartListener2 to listen for events such as activation, closing, and saving of views and editors.
    • When an editor is saved, you can obtain its corresponding IFile and then remove the IFile from your dirtyFiles collection.
    • For example, in the partActivated or partDeactivated method of IPartListener2, you can check if the IEditorPart isDirty().
  3. Handle other status changes :
    • File removal : When IResourceDelta.REMOVED is triggered, the corresponding file should be removed from the dirtyFiles collection.
    • SCM operations (version control) : If a file is restored via a version control system (such as Git, SVN), it may no longer be "dirty". This typically triggers a resource change event, which may require specific logic to handle.

4. Precautions and best practices

  • Performance considerations : IResourceChangeListener will be called when any changes occur in the workspace. Be careful when performing time-consuming operations in the visit method to avoid blocking the UI thread or affecting Eclipse performance.
  • Thread safety : If you access or modify the dirtyFiles collection in multiple threads, make sure to use a synchronization mechanism (such as the synchronized keyword or concurrent collections).
  • Lifecycle management : Register IResourceChangeListener when the plug-in starts, and be sure to remove it when the plug-in stops to avoid resource leaks.
  • Accuracy : The IResourceDelta.CONTENT flag reliably detects modifications to file content. However, determining when a file is "no longer dirty" may require a combination of editor status, save events, and other information.
  • Error handling : Catch CoreException in IResourceDeltaVisitor and do appropriate logging for debugging.

Summarize

Through the IResourceChangeListener and IResourceDelta mechanisms, the Eclipse plug-in can effectively monitor and respond to file content changes in the workspace. Combined with a custom file status tracker and listening for editor save events, developers can build a robust system to identify, manage and operate on all "dirty" files in the project. This approach lays the foundation for various plug-in features that need to handle file modifications (such as automated builds, code analysis, custom save behavior, etc.).

The above is the detailed content of Java Eclipse plug-in development: detecting and tracking 'dirty' files in projects. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling Mar 10, 2026 pm 06:57 PM

What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-

How to configure Java's log output environment_Logback and Log4j2 integration solution How to configure Java's log output environment_Logback and Log4j2 integration solution Mar 10, 2026 pm 08:39 PM

They cannot be used together - Logback and Log4j2 are mutually exclusive, and SLF4J only allows one binding to take effect; if they exist at the same time, a warning will be triggered and one of them will be randomly selected, resulting in log loss or abnormal behavior. A unified appearance and single implementation are required.

How to hot deploy Java applications in IDEA_JRebel plug-in installation and activation tutorial How to hot deploy Java applications in IDEA_JRebel plug-in installation and activation tutorial Mar 10, 2026 pm 08:01 PM

JRebel has basically failed in modern Java development because of its underlying mechanism conflicts with the Java9 module system, SpringBoot2.4 and mainstream IDEs, while IDEA's built-in HotSwap spring-boot-devtools combination is more stable and reliable.

What is the core role of the collection framework in Java_Analysis of the original intention of Java collection design What is the core role of the collection framework in Java_Analysis of the original intention of Java collection design Mar 11, 2026 pm 09:01 PM

The core of the Java collection framework is to solve the three major shortcomings of fixed array length, type insecurity, and redundant operations; it abstracts data relationships through interfaces (Collection is a "bundle of things", Map is "mapping rules"), and generics ensure compilation-time type safety, but implementation class switching may cause implicit performance degradation.

How to configure Java hotkeys in IntelliJ IDEA_Common shortcut key customization guide How to configure Java hotkeys in IntelliJ IDEA_Common shortcut key customization guide Mar 10, 2026 pm 08:06 PM

In IDEA, Ctrl Alt L defaults to "ReformatCode", which can be changed to other operations: first check for conflicts in the Keymap, then remove the original binding and add a new shortcut key for the target operation; pay attention to the focus position, file type and plug-in interference; Mac needs to troubleshoot system-level interception; when team collaboration, the Scheme should be unified and the settings should be synchronized with SettingsRepository.

How to deploy Java production environment on Windows Server_Security enhancement and service-oriented configuration How to deploy Java production environment on Windows Server_Security enhancement and service-oriented configuration Mar 11, 2026 pm 07:18 PM

The boundary between Java version selection and JRE/JDK must be clearly defined in the production environment. Do not use JDK. JRE must be installed on Windows Server—unless you really need diagnostic tools such as jps and jstack to run in the service process. The java.exe and javaw.exe that come with the JDK have the same behavior, but the extra bin directory in the JDK will increase the attack surface. Especially when misconfigured PATH causes the script to call javac.exe, it may be used to execute compiled malicious payloads. Download the build with jdk-xx.jre suffix from https://adoptium.net/ (such as temurin-17.0.2 8-jre), which is not the jdk package installation path.

JavaFX: Copy string contents to system clipboard JavaFX: Copy string contents to system clipboard Mar 13, 2026 am 04:12 AM

This article details how to copy string contents to the system clipboard in a JavaFX application. By utilizing the javafx.scene.input.Clipboard and javafx.scene.input.ClipboardContent classes, developers can easily implement clipboard operations on text data. The article provides clear sample code and usage guidelines to ensure that readers can quickly master and apply this feature in their own projects to improve user experience.

Optimize the Controller layer: introduce DTO mapping and service calling abstraction layer Optimize the Controller layer: introduce DTO mapping and service calling abstraction layer Apr 03, 2026 am 10:00 AM

This article discusses the introduction of an abstraction layer between the Controller and business services in order to solve the problems of overloaded responsibilities and code duplication in the Controller layer in Web application development. This layer is mainly responsible for the mapping of request DTOs and service input DTOs, service calls, and the mapping of service output DTOs and response DTOs. It achieves generalization through generic and functional programming, thereby improving the cleanliness, maintainability and testability of the code.

Related articles