Экземпляром какого класса является поле system err

от admin

Экземпляром какого класса является поле system err

Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Nested Class Summary

Field Summary

Method Summary

Methods inherited from class java.lang.Object

Field Detail

For simple stand-alone Java applications, a typical way to write a line of output data is:

See the println methods in class PrintStream .

Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out , has been redirected to a file or other destination that is typically not continuously monitored.

Method Detail

setIn

First, if there is a security manager, its checkPermission method is called with a RuntimePermission(«setIO») permission to see if it’s ok to reassign the «standard» input stream.

setOut

First, if there is a security manager, its checkPermission method is called with a RuntimePermission(«setIO») permission to see if it’s ok to reassign the «standard» output stream.

setErr

First, if there is a security manager, its checkPermission method is called with a RuntimePermission(«setIO») permission to see if it’s ok to reassign the «standard» error output stream.

console
inheritedChannel

This method returns the channel obtained by invoking the inheritedChannel method of the system-wide default SelectorProvider object.

In addition to the network-oriented channels described in inheritedChannel , this method may return other kinds of channels in the future.

setSecurityManager

If there is a security manager already installed, this method first calls the security manager’s checkPermission method with a RuntimePermission(«setSecurityManager») permission to ensure it’s ok to replace the existing security manager. This may result in throwing a SecurityException .

Otherwise, the argument is established as the current security manager. If the argument is null and no security manager has been established, then no action is taken and the method simply returns.

getSecurityManager
currentTimeMillis

See the description of the class Date for a discussion of slight discrepancies that may arise between «computer time» and coordinated universal time (UTC).

nanoTime

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) — no guarantees are made except that the resolution is at least as good as that of currentTimeMillis() .

Differences in successive calls that span greater than approximately 292 years (2 63 nanoseconds) will not correctly compute elapsed time due to numerical overflow.

The values returned by this method become meaningful only when the difference between two such values, obtained within the same instance of a Java virtual machine, is computed.

For example, to measure how long some code takes to execute:

To compare elapsed time against a timeout, use instead of because of the possibility of numerical overflow.

arraycopy

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

If dest is null , then a NullPointerException is thrown.

If src is null , then a NullPointerException is thrown and the destination array is not modified.

  • The src argument refers to an object that is not an array.
  • The dest argument refers to an object that is not an array.
  • The src argument and dest argument refer to arrays whose component types are different primitive types.
  • The src argument refers to an array with a primitive component type and the dest argument refers to an array with a reference component type.
  • The src argument refers to an array with a reference component type and the dest argument refers to an array with a primitive component type.
  • The srcPos argument is negative.
  • The destPos argument is negative.
  • The length argument is negative.
  • srcPos+length is greater than src.length , the length of the source array.
  • destPos+length is greater than dest.length , the length of the destination array.

Otherwise, if any actual component of the source array from position srcPos through srcPos+length-1 cannot be converted to the component type of the destination array by assignment conversion, an ArrayStoreException is thrown. In this case, let k be the smallest nonnegative integer less than length such that src[srcPos+ k ] cannot be converted to the component type of the destination array; when the exception is thrown, source array components from positions srcPos through srcPos+ k -1 will already have been copied to destination array positions destPos through destPos+ k -1 and no other positions of the destination array will have been modified. (Because of the restrictions already itemized, this paragraph effectively applies only to the situation where both arrays have component types that are reference types.)

identityHashCode
getProperties

First, if there is a security manager, its checkPropertiesAccess method is called with no arguments. This may result in a security exception.

The current set of system properties for use by the getProperty(String) method is returned as a Properties object. If there is no current set of system properties, a set of system properties is first created and initialized. This set of system properties always includes values for the following keys:

Shows property keys and associated values

Key Description of Associated Value
java.version Java Runtime Environment version which may be interpreted as a Runtime.Version
java.vendor Java Runtime Environment vendor
java.vendor.url Java vendor URL
java.home Java installation directory
java.vm.specification.version Java Virtual Machine specification version which may be interpreted as a Runtime.Version
java.vm.specification.vendor Java Virtual Machine specification vendor
java.vm.specification.name Java Virtual Machine specification name
java.vm.version Java Virtual Machine implementation version which may be interpreted as a Runtime.Version
java.vm.vendor Java Virtual Machine implementation vendor
java.vm.name Java Virtual Machine implementation name
java.specification.version Java Runtime Environment specification version which may be interpreted as a Runtime.Version
java.specification.vendor Java Runtime Environment specification vendor
java.specification.name Java Runtime Environment specification name
java.class.version Java class format version number
java.class.path Java class path
java.library.path List of paths to search when loading libraries
java.io.tmpdir Default temp file path
java.compiler Name of JIT compiler to use
os.name Operating system name
os.arch Operating system architecture
os.version Operating system version
file.separator File separator («/» on UNIX)
path.separator Path separator («:» on UNIX)
line.separator Line separator («\n» on UNIX)
user.name User’s account name
user.home User’s home directory
user.dir User’s current working directory

Multiple paths in a system property value are separated by the path separator character of the platform.

Note that even if the security manager does not permit the getProperties operation, it may choose to permit the getProperty(String) operation.

lineSeparator

On UNIX systems, it returns «\n» ; on Microsoft Windows systems it returns «\r\n» .

setProperties

First, if there is a security manager, its checkPropertiesAccess method is called with no arguments. This may result in a security exception.

The argument becomes the current set of system properties for use by the getProperty(String) method. If the argument is null , then the current set of system properties is forgotten.

getProperty

First, if there is a security manager, its checkPropertyAccess method is called with the key as its argument. This may result in a SecurityException.

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

getProperty

First, if there is a security manager, its checkPropertyAccess method is called with the key as its argument.

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

setProperty

First, if a security manager exists, its SecurityManager.checkPermission method is called with a PropertyPermission(key, «write») permission. This may result in a SecurityException being thrown. If no exception is thrown, the specified property is set to the given value.

clearProperty

First, if a security manager exists, its SecurityManager.checkPermission method is called with a PropertyPermission(key, «write») permission. This may result in a SecurityException being thrown. If no exception is thrown, the specified property is removed.

getenv

If a security manager exists, its checkPermission method is called with a RuntimePermission («getenv.»+name) permission. This may result in a SecurityException being thrown. If no exception is thrown the value of the variable name is returned.

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. Environment variables have a more global effect, because they are visible to all descendants of the process which defines them, not just the immediate Java subprocess. They can have subtly different semantics, such as case insensitivity, on different operating systems. For these reasons, environment variables are more likely to have unintended side effects. It is best to use system properties where possible. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH ).

On UNIX systems the alphabetic case of name is typically significant, while on Microsoft Windows systems it is typically not. For example, the expression System.getenv(«FOO»).equals(System.getenv(«foo»)) is likely to be true on Microsoft Windows.

getenv

If the system does not support environment variables, an empty map is returned.

The returned map will never contain null keys or values. Attempting to query the presence of a null key or value will throw a NullPointerException . Attempting to query the presence of a key or value which is not of type String will throw a ClassCastException .

The returned map and its collection views may not obey the general contract of the Object.equals(java.lang.Object) and Object.hashCode() methods.

The returned map is typically case-sensitive on all platforms.

If a security manager exists, its checkPermission method is called with a RuntimePermission («getenv.*») permission. This may result in a SecurityException being thrown.

When passing information to a Java subprocess, system properties are generally preferred over environment variables.

getLogger
getLogger

This method calls the exit method in class Runtime . This method never returns normally.

The call System.exit(n) is effectively equivalent to the call:

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

The call System.gc() is effectively equivalent to the call:

runFinalization

Calling this method suggests that the Java Virtual Machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations.

The call System.runFinalization() is effectively equivalent to the call:

runFinalizersOnExit

If there is a security manager, its checkExit method is first called with 0 as its argument to ensure the exit is allowed. This could result in a SecurityException.

The call System.load(name) is effectively equivalent to the call:

loadLibrary

The call System.loadLibrary(name) is effectively equivalent to the call

mapLibraryName

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2017, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Java I/O by

Get full access to Java I/O and 60K+ other titles, with a free 10-day trial of O’Reilly.

There are also live events, courses curated by job role, and more.

The Console: System.out, System.in, and System.err

The console is the default destination for output written to System.out or System.err and the default source of input for System.in . On most platforms the console is the command-line environment from which the Java program was initially launched, perhaps an xterm (Figure 1.1) or a DOS shell window (Figure 1.2). The word console is something of a misnomer, since on Unix systems the console refers to a very specific command-line shell, rather than being a generic term for command-line shells overall.

Figure 1-1. An xterm console on Unix

A DOS shell console on Windows NT

Figure 1-2. A DOS shell console on Windows NT

Many common misconceptions about I/O occur because most programmers’ first exposure to I/O is through the console. The console is convenient for quick hacks and toy examples commonly found in textbooks, and I will use it for that in this book, but it’s really a very unusual source of input and destination for output, and good Java programs avoid it. It behaves almost, but not completely, unlike anything else you’d want to read from or write to. While consoles make convenient examples in programming texts like this one, they’re a horrible user interface and really have little place in modern programs. Users are more comfortable with a well-defined graphical user interface. Furthermore, the console is unreliable across platforms. The Mac, for example, has no native console. Macintosh Runtime for Java 2 and earlier has a console window that works only for output, but not for input; that is, System.out works but System.in does not. [4] Figure 1.3 shows the Mac console window.

The Mac console, used exclusively by Java programs

Figure 1-3. The Mac console, used exclusively by Java programs

Personal Digital Assistants (PDAs) and other handheld devices running PersonalJava are equally unlikely to waste their small screen space and low resolution on a 1970s-era interface.

Consoles in Applets

As well as being unpredictable across platforms, consoles are also unpredictable across web browsers. Netscape provides a “Java console,” shown in Figure 1.4, that’s used for applets that want to write on System.out . By typing a question mark, you get a list of useful debugging commands that can be executed from the console.

Netscape Navigator’s Java console window

Figure 1-4. Netscape Navigator’s Java console window

The console is turned off by default, and users must explicitly request that it be turned on. Therefore, it’s a bad idea to use it in production applets, though it’s often useful for debugging. Furthermore, mixing and matching a command line and a graphical user interface is generally a bad idea.

Some versions of Microsoft Internet Explorer do not have a visible console. Instead, data written on System.out appears in a log file. On Windows, this file can be found at %Windir%\ java\ javalog.txt . (This probably expands to something like C:\Windows\java\ javalog.txt , depending on the exact value of the %Windir% environment variable). On the Mac the log file is called Java Message Log.html and resides in the same folder as Internet Explorer. To turn this option on, select the Options. menu item from the View menu, click the Advanced tab, then check Enable Java Logging .

If you absolutely must use a console in your applet, the following list shows several third-party consoles that work in Internet Explorer. Some provide additional features over the bare-bones implementation of Netscape. Of course, URLs can get stale rather quickly. If for some reason none of these work for you, you can always do what I did to collect them in the first place: go to http://developer.java.sun.com/developer and search for “console.”

Arial Bardin’s Java Console

Jamie Cansdale’s Java Console and Class Flusher

Frederic Lavigne’s Package fr.l2f

System.out

System.out is the first instance of the OutputStream class most programmers encounter. In fact, it’s often encountered before programmers know what a class or an output stream is. Specifically, System.out is the static out field of the java.lang.System class. It’s an instance of java.io.PrintStream , a subclass of java.io.OutputStream .

System.out corresponds to stdout in Unix or C. Normally, output sent to System.out appears on the console. As a general rule, the console converts the numeric byte data System.out sends to it into ASCII or ISO Latin-1 text. Thus, the following lines write the string “Hello World!” on the console:

System.err

Unix and C programmers are familiar with stderr , which is commonly used for error messages. stderr is a separate file pointer from stdout , but often means the same thing. Generally, stderr and stdout both send data to the console, whatever that is. However, stdout and stderr can be redirected to different places. For instance, output can be redirected to a file while error messages still appear on the console.

System.err is Java’s version of stderr . Like System.out , System.err is an instance of java.io.PrintStream , a subclass of java.io.OutputStream . System.err is most commonly used inside the catch clause of a try / catch block like this:

Finished programs shouldn’t have much need for System.err , but it is useful while you’re debugging.

System.in

System.in is the input stream connected to the console, much as System.out is the output stream connected to the console. In Unix or C terms, System.in is stdin and can be redirected from a shell in the same fashion. System.in is the static in field of the java.lang.System class. It’s an instance of java.io.InputStream , at least as far as is documented.

Past what’s documented, System.in is really a java.io.BufferedInputStream . BufferedInputStream doesn’t declare any new methods, just overrides the ones already declared in java.io.InputStream . Buffered input streams read data in large chunks into a buffer, then parcel it out in requested sizes. This can be more efficient than reading one character at a time. Otherwise, it’s completely transparent to the programmer.

The main significance of this is that each byte is not presented to be read as the user types it on System.in . Instead, input enters the program one line at a time. This allows a user typing into the console to backspace over and correct mistakes. Java does not allow you to put the console into “raw mode,” where each character becomes available as soon as it’s typed, including characters like backspace and delete.

In an application run from the command line, System.in is taken from the window where the program was started; that is, the console. In applets, the same console window that’s used for System.out is also used for System.in ; however, Internet Explorer has no way to read from System.in in an applet. In Netscape, the console is turned off by default, and users must explicitly request that it be turned on.

The user types into the console using the platform’s default character set, typically ASCII or some superset thereof. The data is converted into numeric bytes when read. For example, if the user types “Hello World!” and hits the return or enter key, the following bytes will be read from System.in in this order:

Many programs that run from the command line and read input from System.in require you to enter the “end of stream” character, also known as the “end of file” or EOF character, to terminate a program normally. How this is entered is platform-dependent. On Unix and the Mac, Ctrl-D generally indicates end of stream. On Windows, Ctrl-Z does. In some cases it may be necessary to type this character alone on a line. That is, you may need to hit Return/Ctrl-Z or Return/Ctrl-D before Java will recognize the end of stream.

Redirecting System.out, System.in, and System.err

In a shell you often redirect stdout , stdin , or stderr . For example, to specify that output from the Java program OptimumBattingOrder goes into the file yankees99.out and that input for that program is read from the file yankees99.tab , you might type:

Redirection in a DOS shell is the same. It’s a little more complicated in graphical environments, but not particularly difficult. To give one example, the JBindery tool included in Apple’s Macintosh Runtime for Java, shown in Figure 1.5, provides a simple pop-up menu interface for selecting a file, /dev/null , or a message window as the target of System.out or source for System.in .

Redirecting stdout and stdin from JBindery

Figure 1-5. Redirecting stdout and stdin from JBindery

It’s sometimes convenient to be able to redirect System.out , System.in , and System.err from inside the running program. The following three static methods in the java.lang.System class do exactly that:

For example, to specify that data written on System.out is sent to the file yankees99.out and data read from System.in comes from yankees99.tab , you could write:

These methods are especially useful when making a quick and dirty port of a program that makes heavy use of System.out , System.in , or System.err from an application to an applet. However, there is no absolute guarantee that console redirection will be allowed in all web browsers. Internet Explorer 4.0b2 allowed it, but the released version does not. HotJava 1.1 allows it with the security settings turned down, but not with security at the default level. Netscape Navigator 4.0 and 4.5 and HotJava 1.0 do not allow console redirection.

The SecurityManager class does not have a specific method to test whether or not redirecting System.out or System.err is allowed. However, in Java 1.1 Sun’s JDK checks whether this is permitted by calling checkExec( » setIO » ) . (The source code contains a comment to the effect that there should be a separate method for this sort of check in future versions of Java.) checkExec() determines whether the security manager allows a subprocess called setio to be spawned. The AppletSecurity security manager used by appletviewer in JDK 1.1 always disallows this call.

In Java 2 the security architecture has changed, but the effect is the same. A RuntimePermission object with the name setIO and no actions is passed to AccessController.checkPermission() . This method throws an AccessControlException , a subclass of SecurityException , if redirection is not allowed.

[4] Console input is supported in MRJ 2.1ea2 and presumably later releases.

Get Java I/O 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.

Java: System.out Vs System.in Vs System.err classes and methods.

The java.lang.System class, having three static members (in, out and err) that pre-initialize at JVM startup that’s what no need to initialize. These classes also known as Stream classes.

Out of these System.out is most frequent use by programmers to write output on the console.

System Stream Classes

Here is a list of System Stream classes objects:

  • System.in
  • System.out
  • System.err

System.in

System.in is an InputStream type object which is typically connected to the keyboard input of console programs.

Note: It’s generally used often, Mainly used by beginner-level programmers to insert input from the keyboard. Because when you consider for application-level data is commonly passed to program by:

  • Command-line arguments
  • Configuration files
  • Application GUI

See Also:

System.out

System.out is a PrintStream type used to outputs the data to the console.

Note: It’s the most frequent used Stream object to print out of the program and for debugging about the flow and values.

System.err

System.err is a PrintStream type mainly used to output an error texts to console.

Note: Some of IDE like eclipse show System.err output in the console in red color so that you can easily see error messages.

Example for System .in, System.out and System.err

In this example, you will see, How to insert value to a program by the keyboard by System.in. Output to console by System.out and for any error print by System.err.

System in out and Err Example

Example System.in, System.out and System.err

Output

System in out err result

Exchanging System Streams

By default System Stream class is to console, but we can also change System Streams by programmatical configuration for each type so that InputStream for System.in or OutputStream for System.out or System.err will read and write to the new stream.

  • System.setIn() : This method use to change input stream.
  • System.setOut() : This method use to change output stream.
  • System.setErr() : This method use to change error output stream.

See Also:

System.out Stream Change

In the below example, out will be got to the given file instead of default OutputStream as Console.

Работа с классом Java System (java.lang.System)

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

Кратко о классе Java System

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

Пример работы с классом

Вызов метода из класса java.lang.System выглядит так: System.out.print() — это один из самых простых способов логгирования информации.

Далее рассмотрим различные функции, предоставляемые классом java.lang.System .

Пример использования Array Copy класса Java System

Класс System обеспечивает нативный метод для копирования данных из одного массива в другой. Это встроенный метод, поэтому должен работать быстрее, чем другие способы копирования массива.

Метод System.arraycopy бросает исключение IndexOutOfBoundsException если копирование обратится к данным за пределами границ массива.

Также он бросает ArrayStoreException если элемент в исходном массиве не может быть сохранен в массиве назначения из-за несоответствия типа.

Еще может быть выброшен NullPointerException, если массив источник или массив назначения null .

Читать:
Почему не работает принтер hp laserjet p1102

Похожие статьи