System

Класс java.lang.System является final, все поля и методы являются статическими (static). Он располагает множеством полезных методов для работы. Класс Java System не предоставляет каких-либо публичных конструкторов, поэтому нельзя создать экземпляр этого класса.

Работа с I/O

Поля:

out

The “standard” output stream (PrintStream).

Typically this stream corresponds to display output or another output destination specified by the host environment or user.

in

The “standard” input stream (InputStream).

Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.

err

The “standard” error output stream (PrintStream).

По соглашению этот выходной поток используется для отображения сообщений об ошибках или другой информации, которая должна быть незамедлительно предоставлена пользователю, даже если основной выходной поток (out) был перенаправлен в файл или другое место назначения, которое обычно не контролируется непрерывно.

Методы:

console​()

Returns the unique Console (methods to access the character-based console device) object associated with the current Java virtual machine, if any.

inheritedChannel​()

Returns the Channel (nio) inherited from the entity that created this Java virtual machine.

lineSeparator​()

Returns the system-dependent line separator string.

setErr​(PrintStream err)

Reassigns the “standard” error output stream.

setIn​(InputStream in)

Reassigns the “standard” input stream.

setOut​(PrintStream out)

Reassigns the “standard” output stream.

Работа с Property

clearProperty​(String key)

Removes the system property indicated by the specified key.

getProperties​()

Determines the current system Properties (Properties extends Hashtable<Object,Object> + additional methods for work with properties).

Default properties

getProperty​(String key)

Gets the system property (String) indicated by the specified key.

getProperty​(String key, String def)

Gets the system property (String) indicated by the specified key. def - a default value.

setProperties​(Properties props)

Sets the system properties to the Properties argument.

setProperty​(String key, String value)

Sets the system property indicated by the specified key. Returns the previous value of the system property, or null if it did not have one.

Environment (переменные среды):

System properties and environment variables are both conceptually mappings between names and values. Both mechanisms can be used to pass user-defined information to a Java process.

Переменные среды имеют более глобальный эффект нежели properties, потому что они видны всем потомкам процесса, который их определяет, а не только непосредственному подпроцессу Java.

Переменные среды следует использовать, когда требуется глобальный эффект или когда внешнему системному интерфейсу требуется переменная среды (например, PATH).

getenv​()

Returns an unmodifiable string map (Map<String,String>) view of the current system environment.

getenv​(String name)

Gets the value of the specified environment variable.

Получение текущего времени

currentTimeMillis​()

Returns the current time in milliseconds (long).

Effectively equivalent to the call Date().getTime()

nanoTime​()

Returns the current value of the running Java Virtual Machine’s high-resolution time source, in nanoseconds (long). Возвращаемое значение представляет наносекунды с некоторого фиксированного, но произвольного времени начала (возможно, в будущем, поэтому значения могут быть отрицательными).

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time

Управление состоянием JVM

gc​()

Runs the garbage collector.

Когда управление возвращается из вызова метода, виртуальная машина Java сделала все возможное, чтобы освободить пространство от всех недоступных объектов.

Effectively equivalent to the call Runtime.getRuntime().gc()

runFinalization​()

Runs the finalization methods of any objects pending finalization.

Effectively equivalent to the call Runtime.getRuntime().runFinalization()

exit​(int status)

Terminates the currently running Java Virtual Machine.

Effectively equivalent to the call Runtime.getRuntime().exit(n)

Работа с объектами

arraycopy​(Object src, int srcPos,
Object dest, int destPos, int length)

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

identityHashCode​(Object x)

Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object’s class overrides hashCode().

System.Logger

System.LoggerFinder - The LoggerFinder service is responsible for creating, managing, and configuring loggers to the underlying framework it uses.

System.Logger - Экземпляры System.Logger регистрируют сообщения, которые будут направлены в underlying logging framework, который использует LoggerFinder.

getLogger​(String name)

Returns an instance of System.Logger for the caller’s use.

getLogger​(String name, ResourceBundle bundle)

Returns a localizable instance of System.Logger for the caller’s use.

SecurityManager

The security manager is a class that allows applications to implement a security policy. It allows an application to determine, before performing a possibly unsafe or sensitive operation, what the operation is and whether it is being attempted in a security context that allows the operation to be performed. The application can allow or disallow the operation.

getSecurityManager​()

Gets the system security (SecurityManager) interface.

setSecurityManager​(SecurityManager s)

Sets the System security.

Пример

public class CustomPermission extends BasicPermission {
    public CustomPermission(String name) {
        super(name);
    }

    public CustomPermission(String name, String actions) {
        super(name, actions);
    }
}

public class Service {

    public static final String OPERATION = "my-operation";

    public void operation() {
        SecurityManager securityManager = System.getSecurityManager();
        if (securityManager != null) {
            securityManager.checkPermission(new CustomPermission(OPERATION));
        }
        System.out.println("Operation is executed");
    }
}

Загрузка динамических библиотек

load​(String filename)

Loads the native library specified by the filename argument.

Runtime.getRuntime().load(name)

loadLibrary​(String libname)

Loads the native library specified by the libname argument.

Runtime.getRuntime().loadLibrary(name)

mapLibraryName​(String libname)

Maps a library name into a platform-specific string representing a native library.