Using .gitignore
Learn how to exclude build artifacts and unnecessary files from your Git repository using .gitignore patterns in Java projects.
What is .gitignore?
A .gitignore file is a plain text file placed in your repository root that tells Git which files and directories to intentionally ignore. Any file or folder matching a pattern in .gitignore will not be tracked, staged, or committed.
Why Ignore Files?
Build Artifacts in Java Projects
The Core Rule
Pattern Syntax
Tracked vs Untracked Files
.gitignore only affects untracked files. If a file is already being tracked by Git (was previously committed), adding it to .gitignore will not remove it. You must explicitly untrack it first.
| Untracked File | Already Tracked File | |
|---|---|---|
| Add to .gitignore | ✓ Immediately ignored | ✕ Still tracked |
| Appears in git status | No | Yes (shows changes) |
| Fix if already tracked | N/A | git rm --cached |
How to Set Up .gitignore
Example: Maven Project
Example: Gradle Project
Advanced Patterns
How Git Processes Patterns
Common Java Artifacts to Ignore
Global vs Local .gitignore
| Global (~/.gitignore_global) | Local (.gitignore) | |
|---|---|---|
| Scope | All repos on your machine | This repo only |
| Shared with team? | ✕ No (personal config) | ✓ Yes (committed) |
| Best for | OS files (.DS_Store, Thumbs.db) | Build artifacts (/target, /build) |
| Setup | git config --global core.excludesfile | Create file in project root |
Common Mistakes
Pattern Reference Summary
| Pattern | Meaning | Example Match |
|---|---|---|
| *.class | All .class files in any directory | src/Main.class |
| /target/ | Root-level target directory only | target/app.jar |
| **/build/ | build/ at any depth | module/build/ |
| *.log | All .log files | debug.log |
| !important.log | Re-include despite *.log | important.log |
| config/ | Any directory named config | src/config/ |
Question 1 of 5
What is the primary purpose of a .gitignore file?
Question 2 of 5
In a Maven Java project, which directory contains compiled build artifacts and should be added to .gitignore?
Question 3 of 5
You already committed the /target/ directory, then added it to .gitignore. What happens?
Question 4 of 5
What does the pattern **/build/ match in a .gitignore file?
Question 5 of 5
Given this .gitignore content, which file will not be ignored?
.gitignore contents:
*.log
!error.log
/target/
*.class