
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Methods
- Scala - Functions
- Scala - Methods vs Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala - Polymorphic Functions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - NumericRange
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala Advanced Types
- Scala - Union Types
- Scala - Intersection Types
- Scala - Type Aliases
- Scala - Structural Types
- Scala - Match Expression
- Scala - Singleton Type Operator
- Scala - Abstract Types
- Scala - Dependent Types
- Scala - Abstract Type Bounds
- Scala - Higher-Kinded Types
- Scala - Opaque Type Alias
- Scala - Path-Dependent Types
- Scala - Type Lambdas
- Scala - Type Inference
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Guards
- Scala - Variables in Patterns
- Scala - Type Patterns
- Scala - The Matchable Trait
- Scala - Matching Arrays
- Scala - Matching Lists
- Scala - Matching Tuples
- Scala - Exception Handling
- Scala - Extractors
- Scala - Pattern Bindings
- Scala - Regular Expressions
- Scala - Case Classes
- Scala - Partial Functions
- Scala - Packaging and Imports
- Scala - Implicit Imports
- Scala - Export Clauses
- Scala - Nested Packages
- Scala - Chained Packages
- Scala - Package Objects
- Scala Files I/O
- Scala - Files I/O
- Scala - Writing Files
- Scala - Listing Files
- Scala - Deleting Directories
- Scala - Check File Exists
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Process Management
- Scala - Scaladoc
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala Unit Testing
- Scala - Unit Testing
- Scala - uTest
- Scala - MUnit
- Scala - ScalaTest Runner
- Scala - ScalaMock
- Scala - JUnit
- Scala - Mocking
- Scala - BDD Testing
Scala - Listing Files in a Directory
Scala is open to make use of any Java objects and java.io.File is one of the objects which can be used in Scala programming to read, write, delete files and directories, etc.
Listing Files in a Directory
You can list files in a directory using the list method of Java File class. This method returns an array of strings naming the files and directories in the directory denoted by the abstract pathname.
Example
Following is the example which shows you how to list the files in a directory named testDir −
import java.io._ object Demo { def main(args: Array[String]) = { val directory = new File("testDir") val files = directory.list() if (files != null) { println("Directory contents:") for (file <- files) { println(file) } } else { println("Failed to list directory contents") } } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
The above code will attempt to list the contents of the directory testDir. If the directory exists and its contents are listed successfully, it will print the names of the files and directories within it. If the listing fails for some reason, it will print "Failed to list directory contents".
This will produce the following result -
Directory contents: file1.txt file2.txt subDir
Listing Files with a Specific Extension
You can list files with a specific extension using the listFiles method and a FilenameFilter.
Example
Following is the example which shows you how to list all .txt files in a directory named testDir −
import java.io._ object Demo { def main(args: Array[String]) = { val directory = new File("testDir") val txtFiles = directory.listFiles(new FilenameFilter { def accept(dir: File, name: String): Boolean = name.endsWith(".txt") }) if (txtFiles != null) { println("Text files:") for (file <- txtFiles) { println(file.getName) } } else { println("Failed to list text files") } } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
The above code will attempt to list all .txt files in the directory testDir. If the directory exists and the files are listed successfully, it will print the names of the .txt files within it. If the listing fails for some reason, it will print "Failed to list text files".
This will produce the following result -
Text files: file1.txt file2.txt
Listing Files Recursively
You can list files in a directory and its subdirectories using recursion.
Example
Following is the example which shows you how to list all files in a directory named testDir and its subdirectories −
import java.io._ object Demo { def main(args: Array[String]) = { val directory = new File("testDir") println("Listing files recursively:") listFilesRecursively(directory) } def listFilesRecursively(directory: File): Unit = { val files = directory.listFiles() if (files != null) { for (file <- files) { if (file.isDirectory) { listFilesRecursively(file) } else { println(file.getPath) } } } else { println(s"Failed to list files for directory: ${directory.getPath}") } } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
The above code will attempt to list all files in the directory testDir and its subdirectories. If the directories exist and the files are listed successfully, it will print the paths of the files within them. If the listing fails for some reason, it will print "Failed to list files for directory: directoryPath".
This will produce the following result -
Listing files recursively: testDir/file1.txt testDir/file2.txt testDir/subDir/file3.txt
Listing Hidden Files
You can list hidden files using the isHidden method of the File class.
Example
Following is the example which shows you how to list hidden files in a directory named testDir −
import java.io._ object Demo { def main(args: Array[String]) = { val directory = new File("testDir") val hiddenFiles = directory.listFiles(new FileFilter { def accept(file: File): Boolean = file.isHidden }) if (hiddenFiles != null) { println("Hidden files:") for (file <- hiddenFiles) { println(file.getName) } } else { println("Failed to list hidden files") } } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
The above code will attempt to list hidden files in the directory testDir. If the directory exists and the files are listed successfully, it will print the names of the hidden files within it. If the listing fails for some reason, it will print "Failed to list hidden files".
This will produce the following result -
Hidden files: .hiddenFile1 .hiddenFile2
Listing Files with Detailed Information
You can list files with detailed information, like file size and last modified date using the length and lastModified methods of the File class.
Example
Following is the example which shows you how to list files with detailed information in a directory named testDir −
import java.io._ import java.text.SimpleDateFormat object Demo { def main(args: Array[String]) = { val directory = new File("testDir") val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val files = directory.listFiles() if (files != null) { println("Files with detailed information:") for (file <- files) { val lastModified = dateFormat.format(file.lastModified()) println(s"Name: ${file.getName}, Size: ${file.length()} bytes, Last Modified: $lastModified") } } else { println("Failed to list files") } } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
The above code will attempt to list files with detailed information in the directory testDir. If the directory exists and the files are listed successfully, it will print the names, sizes, and last modified dates of the files within it. If the listing fails for some reason, it will print "Failed to list files".
This will produce the following result -
Files with detailed information: Name: file1.txt, Size: 1024 bytes, Last Modified: 2023-07-15 12:34:56 Name: file2.txt, Size: 2048 bytes, Last Modified: 2023-07-16 08:22:33
Handling Exceptions When Listing Files
When working with file operations, it is important to handle exceptions like SecurityException and IOException to make your code more robust.
Example
Following is the example which shows you how to handle exceptions when listing files −
import java.io.File object Demo { def main(args: Array[String]): Unit = { try { val directory = new File("/restricted_directory") val files = directory.listFiles() if (files != null) { files.foreach(file => println(file.getName)) } else { println("No files found or directory does not exist.") } } catch { case se: SecurityException => println(s"Permission denied: ${se.getMessage}") case ioe: java.io.IOException => println(s"I/O error occurred: ${ioe.getMessage}") case e: Exception => println(s"An unexpected error occurred: ${e.getMessage}") } } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
If an error occurs, the program will print an appropriate error message.
This will produce the following result -
Permission denied: [error message]