Chapter 2. Interacting with the Environment
2.0 Introduction
This chapter describes how your Java program can deal with its immediate surroundings with what we call the runtime environment. In one sense, everything you do in a Java program using almost any Java API involves the environment. Here we focus more narrowly on things that directly surround your program. Along the way we’ll be introduced to the System
class, which knows a lot about your particular system.
Two other runtime classes deserve brief mention. The
first, java.lang.Runtime
, lies behind many of the methods in the System
class. System.exit()
, for example, just calls Runtime.exit()
. Runtime
is technically part of the environment, but the only time we use it
directly is to run other programs, which is covered in
Recipe 18.1.
2.1 Getting Environment Variables
Problem
You want to get the value of environment variables from within your Java program.
Solution
Use System.getenv()
.
Discussion
The seventh edition of Unix, released in 1979, had a new feature known as environment
variables. Environment variables are in all modern Unix systems (including macOS) and
in most later command-line systems, such as the DOS or Command Prompt in Windows, but they are
not in some older platforms or other Java runtimes. Environment variables are commonly
used for customizing an individual computer user’s runtime environment, hence the name. To
take one familiar example, on Unix or DOS the environment variable PATH
determines ...
Get Java Cookbook, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.