
- 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 - Check If a File or Path Exists
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.
Checking if given file Exists
You can check if given file exists using the exists method of Java File class. This method returns true if the file (or directory) denoted by the abstract pathname exists, and false otherwise.
Example
Following is the example which shows you how to check if a file named test.txt exists −
import java.io._ object Demo { def main(args: Array[String]) = { val file = new File("test.txt") if (file.exists()) { println("File exists") } else { println("File does not exist") } } }
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 check if the file test.txt exists. If the file exists, it will print "File exists". If the file does not exist, it will print "File does not exist".
This will produce the following result -
File exists
Checking if given directory Exists
You can check if given directory exists similarly to checking if a file exists.
Example
Following is the example which shows you how to check if a directory named testDir exists −
import java.io._ object Demo { def main(args: Array[String]) = { val directory = new File("testDir") if (directory.exists()) { println("Directory exists") } else { println("Directory does not exist") } } }
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 check if the directory testDir exists. If the directory exists, it will print "Directory exists". If the directory does not exist, it will print "Directory does not exist".
This will produce the following result -
Directory exists
Checking if given path is file
You can check if given path is a file using isFile method of the File class. This method returns true if the file denoted by the abstract pathname is a normal file, and false otherwise.
Example
Following is the example which shows you how to check if a path named test.txt is a file −
import java.io._ object Demo { def main(args: Array[String]) = { val file = new File("test.txt") if (file.isFile) { println("Path is a file") } else { println("Path is not a file") } } }
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 check if the path test.txt is a file. If the path is a file, it will print "Path is a file". If the path is not a file, it will print "Path is not a file".
This will produce the following result -
Path is a file
Checking if given path is directory
You can check if given path is a directory using isDirectory method of the File class. This method returns true if the file denoted by the abstract pathname is a directory, and false otherwise.
Example
Following is the example which shows you how to check if a path named testDir is a directory −
import java.io._ object Demo { def main(args: Array[String]) = { val directory = new File("testDir") if (directory.isDirectory) { println("Path is a directory") } else { println("Path is not a directory") } } }
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 check if the path testDir is a directory. If the path is a directory, it will print "Path is a directory". If the path is not a directory, it will print "Path is not a directory".
This will produce the following result -
Path is a directory
Checking if given file Readable
You can check if given file is readable using canRead method of the File class. This method returns true if the file denoted by the abstract pathname can be read, and false otherwise.
Example
Following is the example which shows you how to check if a file named test.txt is readable −
import java.io._ object Demo { def main(args: Array[String]) = { val file = new File("test.txt") if (file.canRead) { println("File is readable") } else { println("File is not readable") } } }
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 check if the file test.txt is readable. If the file is readable, it will print "File is readable". If the file is not readable, it will print "File is not readable".
This will produce the following result -
File is readable
Checking if given file Writable
You can check if given file is writable using canWrite method of the File class. This method returns true if the file denoted by the abstract pathname can be written, and false otherwise.
Example
Following is the example which shows you how to check if a file named test.txt is writable −
import java.io._ object Demo { def main(args: Array[String]) = { val file = new File("test.txt") if (file.canWrite) { println("File is writable") } else { println("File is not writable") } } }
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 check if the file test.txt is writable. If the file is writable, it will print "File is writable". If the file is not writable, it will print "File is not writable".
This will produce the following result -
File is writable
Checking if given file Executable
You can check if given file is executable using canExecute method of the File class. This method returns true if the file denoted by the abstract pathname can be executed, and false otherwise.
Example
Following is the example which shows you how to check if a file named test.txt is executable −
import java.io._ object Demo { def main(args: Array[String]) = { val file = new File("test.txt") if (file.canExecute) { println("File is executable") } else { println("File is not executable") } } }
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 check if the file test.txt is executable. If the file is executable, it will print "File is executable". If the file is not executable, it will print "File is not executable".
This will produce the following result -
File is executable
Handling Exceptions When Checking File Properties
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 checking file properties −
import java.io._ object Demo { def main(args: Array[String]) = { try { val file = new File("test.txt") if (file.exists()) { println("File exists") } else { println("File does not exist") } } catch { case ex: SecurityException => println("Permission denied: " + ex.getMessage) case ex: IOException => println("An IO error occurred: " + ex.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]