Showing posts with label Java File Handling. Show all posts
Showing posts with label Java File Handling. Show all posts

Top 10 Java Projects for Beginners with Source Code and Examples

Top 10 Java Projects & Programs with Source Code

Welcome to my Java Projects & Programs collection — a curated list of 10 practical Java projects that every beginner, student, and interview candidate should build. 🎯

Whether you're learning Java for the first time, building a portfolio for placements, or preparing for technical interviews, these projects will strengthen your understanding of:

  • Core Java — loops, arrays, strings, conditionals
  • GUI Programming — Java Swing components, layouts, events
  • File Handling & Networking — uploading data to a server, file I/O
  • Third-Party Libraries — Barcode generation using ZXing

Each link below takes you to a detailed tutorial with complete source code, line-by-line explanation, and output screenshots. Bookmark this page and build one project per week!

🖥️ Desktop & GUI Projects (Swing)

These projects use Java Swing — the built-in GUI toolkit for creating desktop applications. Perfect for learning event handling, layouts, and component design.

  1. Dynamic Calculator using Scanner — Build a command-line calculator that takes user input dynamically and performs arithmetic operations.
  2. Custom Register Form using Java Swing — Design a registration form with text fields, buttons, and validation using Swing components.
  3. Upload Data to Server using Java — Learn how to send form data from a Java client to a server using HTTP communication.
  4. File Upload using Java Swing — Build a file uploader with file chooser dialog, progress feedback, and server integration.
  5. Lock Window using Java Swing — Implement a security lock screen that prevents interaction until a password is entered.

🛠️ Core Java Utility Programs

These programs strengthen your core Java skills — arrays, third-party libraries, and real-world utilities.

  1. Find Max and Min Value in an Array — Classic interview program using a single loop to find both extremes.
  2. Create Barcode using Java — Generate real barcode images using the ZXing library and save them to disk.

📝 String Manipulation Programs

String questions are the #1 topic in Java coding interviews. Master these before your next interview round.

  1. Find Number of Words in a Given String — Count words using split() and StringTokenizer.
  2. Find Smallest Word in a Given String — Compare word lengths and return the smallest one.
  3. Find Largest Word in a Given String — Find the longest word using loops and length comparison.

🚀 What to Build Next

Once you've completed all 10 projects above, here's your roadmap for the next level:

  1. JavaFX Desktop Apps — modern replacement for Swing
  2. Spring Boot REST API — build a real backend service
  3. Android App — apply Java to mobile development
  4. JDBC + MySQL Project — connect Java to a database
  5. Mini Project — Library Management, Student Management, or ATM System

💡 Pro Tip: Don't just copy-paste the code. Type it out, run it, break it, and fix it. That's how you build real programming intuition!

Final Thoughts

These 10 Java projects form a solid foundation for your Java journey. They cover command-line programs, GUI applications, file handling, third-party libraries, and string manipulation — the exact mix employers want to see in a junior developer's portfolio.

Practice them one at a time, understand the logic, then extend them with your own features. Consistency beats intensity — 1 hour a day is enough to become job-ready in 3–4 months.

File Search in Java Using Files.walk() and File Class with Examples

File Search in Java: How to Search Files and Folders

Searching files and folders is a common task in desktop tools, build scripts, and admin utilities. Java gives you two ways to do it: the older File class with recursion, and the newer Files.walk() from NIO.2. This page shows both with working examples.

Method 1: Using Files.walk (modern approach)

This is the recommended way. It is concise, uses streams, and handles deep directory trees cleanly.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FileSearch {

    public static void main(String[] args) throws IOException {

        Path start = Paths.get("C:/projects");
        String targetName = "application.properties";

        try (Stream<Path> stream = Files.walk(start)) {
            List<Path> matches = stream
                    .filter(Files::isRegularFile)
                    .filter(p -> p.getFileName().toString().equals(targetName))
                    .collect(Collectors.toList());

            for (Path p : matches) {
                System.out.println(p);
            }
        }
    }
}

Output: Every full path where application.properties exists under C:/projects.

Method 2: Using the File class with recursion (older approach)

Use this only if you are on legacy code that predates Java 7. For new code, use Files.walk().

import java.io.File;

public class FileSearchOld {

    public static void search(File folder, String targetName) {
        File[] files = folder.listFiles();
        if (files == null) return;

        for (File f : files) {
            if (f.isDirectory()) {
                search(f, targetName);
            } else if (f.getName().equals(targetName)) {
                System.out.println(f.getAbsolutePath());
            }
        }
    }

    public static void main(String[] args) {
        File root = new File("C:/projects");
        search(root, "application.properties");
    }
}

Output: Same result, but written with older Java APIs.

Searching by extension instead of exact name

Most real use cases need "find all .log files" rather than a single exact name. Change the filter:

List<Path> logs = stream
        .filter(Files::isRegularFile)
        .filter(p -> p.getFileName().toString().endsWith(".log"))
        .collect(Collectors.toList());

Searching by file size

Files.walk() returns Path objects. Use Files.size(path) inside the filter to find files larger than a threshold:

List<Path> largeFiles = stream
        .filter(Files::isRegularFile)
        .filter(p -> {
            try {
                return Files.size(p) > 10 * 1024 * 1024; // 10 MB
            } catch (IOException e) {
                return false;
            }
        })
        .collect(Collectors.toList());

Searching by modified date

Use Files.getLastModifiedTime(path) to filter files modified after a given timestamp:

Instant cutoff = Instant.now().minus(7, ChronoUnit.DAYS);

List<Path> recent = stream
        .filter(Files::isRegularFile)
        .filter(p -> {
            try {
                return Files.getLastModifiedTime(p).toInstant().isAfter(cutoff);
            } catch (IOException e) {
                return false;
            }
        })
        .collect(Collectors.toList());

Common errors and how to fix them

Error Cause Fix
NoSuchFileException The starting path does not exist. Check the path. Use Files.exists(Paths.get(...)) before walking.
AccessDeniedException The process lacks read permission on some folder. Catch the exception in the stream or skip inaccessible directories.
StackOverflowError (recursive File approach) Very deep directory tree hits the recursion limit. Use Files.walk(), which is iterative and does not use stack frames.
Unhandled IOException Forgetting to wrap Files.walk() in a try block. Use try-with-resources around the stream.

Where to go next

You now know how to search files and folders in Java with both the old File class and the modern Files.walk() API.

If you remember one thing, remember this: use Files.walk() for new code. It is safer, shorter, and handles deep trees without stack overflow.

If you want to go deeper, try these next steps:

  • Add a filter for file extension and run it on a real project directory.
  • Try searching for files modified in the last 24 hours. Use Files.getLastModifiedTime().
  • Wrap the stream in parallel() and compare speed on a large folder. Watch out for permission exceptions in parallel mode.
  • Move on to WatchService. It lets you watch a folder and react to files being created, modified, or deleted in real time.