Fundamentals of Text Data Manipulation in Kotlin

Introduction

Welcome to the first lesson in our course on "Fundamentals of Text Data Manipulation." This lesson will introduce you to the essential task of reading text files in Kotlin. Text files serve as a fundamental data source in programming, often used for storing data, configuration files, and logs. Being able to open and read files in Kotlin is a foundational skill you'll often rely on when working with data. By the end of this lesson, you will be able to read the entire contents of a text file into a string using Java's Files.readString method, facilitated by the Paths class, a crucial capability for various data manipulation tasks. Let's get started!

Working with File Paths

A file path is an address that indicates where a file is located in your system's storage. This path guides your program on where to find or save a file. There are two types of file paths commonly used:

  • Absolute Path: This is the complete path to a file, starting from the root directory. Here are examples across different operating systems:

    • Linux: /home/user/documents/input.txt
    • macOS: /Users/user/documents/input.txt
    • Windows: C:\Users\user\documents\input.txt
  • Relative Path: This path is relative to the directory in which your application is currently executing. For example, documents/input.txt assumes your executable is running from the user directory in these examples.

Here's how you can specify a file path in Kotlin:

val filePath = "input.txt"  // Relative path

Ensure your Kotlin program and the text file are in the same directory if using a relative path. Otherwise, consider using the absolute path to ensure your program can locate your file correctly.

Defining Relative Paths with Examples

When working with relative paths in Kotlin, it's important to understand your directory structure. Here are a few examples with file trees:

  1. Example 1:

    File Tree:

    project/
    ├── program
    └── data/
        └── input.txt

    Relative Path:

    val filePath = "data/input.txt"
  2. Example 2:

    File Tree:

    user/
    ├── documents/
    │   └── program
    └── input.txt

    Relative Path:

    val filePath = "../input.txt"

    The .. indicates moving up to the parent directory. This approach works similarly across platforms like macOS/Linux and Windows.

  3. Example 3:

    File Tree:

    application/
    ├── scripts/
    │   ├── program1
    │   └── program2
    └── resources/
        └── input.txt

    Relative Path (works for both program2 and program1):

    val filePath = "../resources/input.txt"

These examples demonstrate how relative paths are determined by the program's current working directory.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal