Java system out error

As I know both out and err are of same class PrintStream. Can anybody tell me how they differ...how they changed their behaviour?

As I know both out and err are of same class PrintStream. Can anybody tell me how they differ…how they changed their behaviour?

Ash's user avatar

Ash

9,1862 gold badges24 silver badges32 bronze badges

asked May 24, 2010 at 11:53

sap's user avatar

1

The difference is not evident because by default in most of the Operating Systems they are written to the console (same file, console is also a file). However, you can have System.out write to a file, and System.err write to the console (monitor) — this is just one scenario.

Write a program that emits both System.out and System.err messages, and try this:

java MyProgram > out.txt 2> err.txt # On a *NIX.

System.out messages will go to out.txt and System.err messages will to err.txt. Basic point to remember is to think of System.out and System.err as streams to files (which is what they are) instead of a mechanism to output on the monitor, which is what I assumed as a beginner.

answered May 24, 2010 at 11:58

Srikanth's user avatar

SrikanthSrikanth

11.7k23 gold badges71 silver badges90 bronze badges

0

They go to the system stdout and stderr streams respectively. On most OSes these are distinct and can be sent to different places. For example, this might be useful if your program’s output was to be parsed by another program — if it needed to report an error, stderr would normally be the better place for it as you might have set it up to get a human’s attention.

answered May 24, 2010 at 11:57

crazyscot's user avatar

crazyscotcrazyscot

11.7k2 gold badges38 silver badges40 bronze badges

They have the same behavior. But first (out) is a reference to standard output stream (by default it’s a console). And second (err) is a reference to standard error stream (by default it’s a console too).

But if you want, you can change a reference, or you can add a wrapper/filter to each of them.

My IDE, for example, shows output from err stream in red colors.

answered May 24, 2010 at 11:58

Roman's user avatar

RomanRoman

63.3k91 gold badges234 silver badges328 bronze badges

System.out sends the output to the standard output stream. System.err sends the output to the standard error stream.
By default both of these write to the console.

However the benefit is that the two stream can be redirected so you could have the system.out output redirected to your normal log file and you could have the System.err output redirected to an error log.

answered May 24, 2010 at 12:02

Robben_Ford_Fan_boy's user avatar

As I know both out and err are of same class PrintStream. Can anybody tell me how they differ…how they changed their behaviour?

Ash's user avatar

Ash

9,1862 gold badges24 silver badges32 bronze badges

asked May 24, 2010 at 11:53

sap's user avatar

1

The difference is not evident because by default in most of the Operating Systems they are written to the console (same file, console is also a file). However, you can have System.out write to a file, and System.err write to the console (monitor) — this is just one scenario.

Write a program that emits both System.out and System.err messages, and try this:

java MyProgram > out.txt 2> err.txt # On a *NIX.

System.out messages will go to out.txt and System.err messages will to err.txt. Basic point to remember is to think of System.out and System.err as streams to files (which is what they are) instead of a mechanism to output on the monitor, which is what I assumed as a beginner.

answered May 24, 2010 at 11:58

Srikanth's user avatar

SrikanthSrikanth

11.7k23 gold badges71 silver badges90 bronze badges

0

They go to the system stdout and stderr streams respectively. On most OSes these are distinct and can be sent to different places. For example, this might be useful if your program’s output was to be parsed by another program — if it needed to report an error, stderr would normally be the better place for it as you might have set it up to get a human’s attention.

answered May 24, 2010 at 11:57

crazyscot's user avatar

crazyscotcrazyscot

11.7k2 gold badges38 silver badges40 bronze badges

They have the same behavior. But first (out) is a reference to standard output stream (by default it’s a console). And second (err) is a reference to standard error stream (by default it’s a console too).

But if you want, you can change a reference, or you can add a wrapper/filter to each of them.

My IDE, for example, shows output from err stream in red colors.

answered May 24, 2010 at 11:58

Roman's user avatar

RomanRoman

63.3k91 gold badges234 silver badges328 bronze badges

System.out sends the output to the standard output stream. System.err sends the output to the standard error stream.
By default both of these write to the console.

However the benefit is that the two stream can be redirected so you could have the system.out output redirected to your normal log file and you could have the System.err output redirected to an error log.

answered May 24, 2010 at 12:02

Robben_Ford_Fan_boy's user avatar

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.

An xterm console on Unix

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:Windowsjava
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.”

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:

byte[] hello = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 10, 
                13};
System.out.write(hello);

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:

try {
  // Do something that may throw an exception.
}
catch (Exception e) {
  System.err.println(e);
}

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:

72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 10, 13

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:

% java OptimumBattingOrder < yankees99.tab > yankees99.out

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:

public static void setIn(InputStream in)
public static void setOut(PrintStream out)
public static void setErr(PrintStream err)

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:

System.setIn(new FileInputStream("yankees99.tab"));
System.setOut(new PrintStream(new FileOutputStream("yankees99.out")));

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.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    System.out is a PrintStream to which we can write characters.  It outputs the data we write to it on the Command Line Interface console/terminal. It is mostly used for console applications/programs to display the result to the user. It can be also useful in debugging small programs.

    Syntax:

    System.out.println("Your Text which you want to display");

    Example:

    Java

    import java.io.*;

    class GFG {

        public static void main(String[] args)

        {

            System.out.println("GeeksForGeeks!");

        }

    }

    Now let us come onto the next concept of System.err which is also very closely related to System.out.System.err is also a print stream. It works the same as System.out. It is mostly used to output error texts. Some programs (like Eclipse) will show the output to System.err in red text, to make it more obvious that it is error text. 

    Syntax:

    System.err.println("Your Text which you want to display");

    Example

    Java

    import java.io.*;

    class GFG {

        public static void main(String[] args)

        {

            System.err.println("GeeksForGeeks!");

        }

    }

    Output:

    GeeksForGeeks!

    Note:

    • System.err and System.out both are defined in System class as reference variable of PrintStream class as:
    public final static PrintStream out = null;
    public final static PrintStream err = null;
    • Both outputs are displayed on the same console, Most of the IDEs differentiate the error output with red color.
    • We can reconfigure the streams so that for example, System.out still prints to the console but System.err writes to a file.

    Now let us finally conclude out the differences between the two which are depicted below in tabular format as follows:

    System.out.println() System.err.println() 
    System.out.println() will print to the standard out of the system. System.err.println() will print to the standard error.
    System.out.println() is mostly used to display results on the console. System.err.println( is mostly used to output error texts.
    It gives output on the console with the default(black) color. It also gives output on the console but most of the IDEs give it a red color to differentiate.

    1. Introduction

    In this post, we feature a comprehensive article on Java System.in System.out System.error. Java has provided java.lang.System class since version 1.0. The System class contains a static System.in for the standard keyboard input, static System.out for the system console output, and static System.err for error output streams to the system console. Here are the definitions:

    static InputStream in - the "standard" input stream.
    static PrintStream out - the "standard" output stream.
    static PrintStream err - the "standard" error output stream.
    static void setIn​(InputStream in) - reassigns the "standard" input stream.
    static void setOut​(PrintStream out) - reassigns the "standard" output stream.
    static void setErr​(PrintStream err) - reassigns the "standard" error output stream.

    Java abstract InputStream class models the input streams of bytes. We can use the System.setIn method to change the input stream to any of the following classes:

    • AudioInputStream
    • ByteArrayInputStream
    • FileInputStream
    • FilterInputStream
    • ObjectInputStream
    • PipedInputStream
    • SequenceInputStream
    • StringBufferInputStream.

    Java PrintStream class is a subclass from FileOutputStream. We can use the setOut and setErr methods to change the output and error output streams.

    In this example, I will demonstrate how to 

    • read inputs from System.in
    • write outputs to System.out
    • write error outputs to System.err
    • re-assign System.in from FileInputStream, URL, and ByteArrayInputStream
    • re-assign System.out to a file
    • re-assign System.err to a file

    2. Technologies used

    The example code in this article was built and run using:

    • Java 1.11
    • Maven 3.3.9
    • Eclipse Oxygen
    • JUnit 4.12

    3. Maven Project

    3.1 Dependency

    Add JUnit to the pom.xml.

    pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<groupId>jcg.zheng.demo</groupId>
    	<artifactId>java-system-in-out-error-demo</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<build>
    		<sourceDirectory>src</sourceDirectory>
    		<plugins>
    			<plugin>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<version>3.8.0</version>
    				<configuration>
    					<release>11</release>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    	<dependencies>
    		<dependency>
    			<groupId>junit</groupId>
    			<artifactId>junit</artifactId>
    			<version>4.12</version>
    		</dependency>
    	</dependencies>
    </project>

    3.2 InputStreamHelper

    In this step, I will create three methods to change System.in to use ByteArrayInputStream, FileInputStream, and URL.

    • setIn_from_ByteArrayInputStream(String msg) – Creates a ByteArrayInputStream from the given string message and reset System.in with it.
    • setIn_from_FileInputStream(String fileName) – Creates a FileInputStream from the given file name and reset System.in with it.
    • setIn_from_URL(String url) – Creates an InputStream from the given url and reset System.in with it.

    InputStreamHelper .java

    package jcg.zheng.demo;
    
    import java.io.ByteArrayInputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class InputStreamHelper {
    
    	public static void setIn_from_ByteArrayInputStream(String msg) {
    		ByteArrayInputStream binput = new ByteArrayInputStream(msg.getBytes());
    		System.setIn(binput);
    	}
    
    	public static void setIn_from_FileInputStream(String fileName) throws FileNotFoundException {
    		FileInputStream in_file = new FileInputStream(fileName);
    		System.setIn(in_file);
    	}
    
    	public static void setIn_from_URL(String url) throws MalformedURLException, IOException {
    		InputStream in_file = new URL(url).openStream();
    		System.setIn(in_file);
    	}
    
    }
    

    3.3 PrintStreamHelper

    In this step, I will create three methods to change the System.out and System.err to use FileOutputStream.

    PrintStreamHelper.java

    package jcg.zheng.demo;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    
    public class PrintStreamHelper {
    
    	public static void setError_from_File(String filename) throws FileNotFoundException {
    		PrintStream error_file = new PrintStream(filename);
    		System.setErr(error_file);
    	}
    
    	public static void setOut_from_File(String filename) throws FileNotFoundException {
    		PrintStream out_file = new PrintStream(filename);
    		System.setOut(out_file);
    	}
    
    	public static void setOut_from_OutStream(String filename) throws FileNotFoundException {
    		PrintStream output = new PrintStream(new FileOutputStream(filename));
    		System.setOut(output);
    	}
    }

    3.4 ScannerApp

    In this step, I will create a ScannerApp class to read inputs from System.in, write data to System.out, and write the exception message to System.err.

    ScannerApp.java

    package jcg.zheng.demo;
    
    import java.util.Scanner;
    
    public class ScannerApp {
    
    	public static void main(String[] argu) {
    		ScannerApp sapp = new ScannerApp();
    		System.out.println("Enter anything from the keyboard:");
    		sapp.scan_in_write_out_and_log_error();
    	}
    
    	public String scan_in_write_out_and_log_error() {
    		String ret = null;
    
    		try (Scanner sc = new Scanner(System.in)) {
    			while (sc.hasNextLine()) {
    				String valueEntered = sc.nextLine();
    				ret = valueEntered;
    				System.out.println("Value from System.in:" + ret);
    				if ("q".equalsIgnoreCase(valueEntered)) {
    					System.out.println("Bye!");
    					System.exit(0);
    				}
    
    				try {
    					Integer.parseInt(valueEntered);
    				} catch (NumberFormatException e) {
    					System.err.println("Caught NumberFormatException " + e.getMessage());
    
    				}
    			}
    		}
    		return ret;
    	}
    }
    

    Execute it as a Java application and capture the output.

    Output

    Enter anything from the keyboard:
    a
    Value from System.in:a
    Caught NumberFormatException For input string: "a"
    12
    Value from System.in:12
    q
    Value from System.in:q
    Bye!
    

    3.5 InputStreamReaderApp

    In this step, I will create an InputStreamReaderApp class to read inputs from System.in, write data to System.out, and write the exception message to System.err.

    InputStreamReaderApp.java

    package jcg.zheng.demo;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class InputStreamReaderApp {
    	public static void main(String[] argu) {
    		InputStreamReaderApp iApp = new InputStreamReaderApp();		
    		System.out.println("Enter anything from the keyboard (q- quit):");		 
    		iApp.read_in_write_out_and_log_error();
    		
    	}
    
    	public String read_in_write_out_and_log_error() {
    		String ret = null;
    		try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
    			String strCurrentLine = null;
    
    			while ((strCurrentLine = br.readLine()) != null) {
    				System.out.println(strCurrentLine);
    				if ("q".equalsIgnoreCase(strCurrentLine)) {
    					System.out.println("Bye!");
    					ret = "Bye";
    					System.exit(0);
    				} else {
    					System.out.println("Value from System.in:" + strCurrentLine);
    					try {
    						ret = String.format("%4d", Integer.parseInt(strCurrentLine));
    					} catch (NumberFormatException e) {
    						ret = "Error";
    						System.err.println("Caught NumberFormatException " + e.getMessage());
    					}
    				}
    			}
    
    		} catch (IOException e) {
    			System.err.println("Caught Exception " + e.getMessage());
    			ret = "Error";
    		}
    		return ret;
    	}
    }
    

    Execute it as a Java application and capture the output.

    Output

    Enter anything from the keyboard (q- quit):
    this will throw exception as it is not a number
    this will throw exception as it is not a number
    Value from System.in:this will throw exception as it is not a number
    Caught NumberFormatException For input string: "this will throw exception as it is not a number"
    12
    12
    Value from System.in:12
    34
    34
    Value from System.in:34
    q
    q
    Bye!
    

    4. JUnit Tests

    I will create two JUnit classes to demonstrate how to read data from System.in, write the outputs to System.out, and write the error outputs to System.err.

    4.1 ScannerAppTest

    In this step, I will create four test methods:

    • test_url_as_in – resets System.in from a URL
    • test_bytearray_as_in – resets System.in from a ByteArrayInputStream
    • test_file_as_in_out – re-assigns a file to System.in and System.out
    • test_file_as_in_out_error – re-assigns a file to System.in, System.out , and System.err

    ScannerAppTest.java

    package jcg.zheng.demo;
    
    import static org.junit.Assert.assertEquals;
    import static org.junit.Assert.assertNotNull;
    
    import java.io.FileNotFoundException;
    
    import org.junit.Test;
    
    public class ScannerAppTest {
    
    	ScannerApp scannerApp = new ScannerApp();
    
    	@Test
    	public void test_bytearray_as_in() {
    		InputStreamHelper.setIn_from_ByteArrayInputStream("hello");
    		String demo = scannerApp.scan_in_write_out_and_log_error();
    		assertEquals("hello", demo);
    	}
    
    
    	@Test
    	public void test_file_as_in_out() {
    		try {
    			PrintStreamHelper.setOut_from_OutStream("data/error_file.log");
    			InputStreamHelper.setIn_from_FileInputStream("data/scan_in_file.txt");
    			String entered = scannerApp.scan_in_write_out_and_log_error();
    			assertNotNull(entered);
    
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		}
    	}
    
    	@Test
    	public void test_file_as_in_out_error() {
    		try {
    			InputStreamHelper.setIn_from_FileInputStream("data/scan_in_file.txt");
    			PrintStreamHelper.setError_from_File("data/error_file.log");
    			PrintStreamHelper.setOut_from_File("data/out_file.txt");
    
    			String demo = scannerApp.scan_in_write_out_and_log_error();
    			assertEquals("qest", demo);
    
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		}
    
    	}
    
    	@Test
    	public void test_url_as_in() {
    		try {
    			InputStreamHelper.setIn_from_URL("https://gmail.com");
    			String lastStr = scannerApp.scan_in_write_out_and_log_error();
    			assertNotNull(lastStr);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Execute mvn test -Dtest=ScannerAppTest and capture the output.

    Output

    C:MaryZhengWorkspacesjdk12java-system-in-out-error-demo>mvn test -Dtest=ScannerAppTest
    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------< jcg.zheng.demo:java-system-in-out-error-demo >------------
    [INFO] Building java-system-in-out-error-demo 0.0.1-SNAPSHOT
    [INFO] --------------------------------[ jar ]---------------------------------
    [INFO]
    [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-system-in-out-error-demo ---
    [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] skip non existing resourceDirectory C:MaryZhengWorkspacesjdk12java-system-in-out-error-demosrcmainresources
    [INFO]
    [INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ java-system-in-out-error-demo ---
    [INFO] Changes detected - recompiling the module!
    [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
    [INFO] Compiling 6 source files to C:MaryZhengWorkspacesjdk12java-system-in-out-error-demotargetclasses
    [INFO]
    [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ java-system-in-out-error-demo ---
    [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] skip non existing resourceDirectory C:MaryZhengWorkspacesjdk12java-system-in-out-error-demosrctestresources
    [INFO]
    [INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ java-system-in-out-error-demo ---
    [INFO] Nothing to compile - all classes are up to date
    [INFO]
    [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ java-system-in-out-error-demo ---
    [INFO] Surefire report directory: C:MaryZhengWorkspacesjdk12java-system-in-out-error-demotargetsurefire-reports
    
    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running jcg.zheng.demo.ScannerAppTest
    Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.101 sec
    
    Results :
    
    Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
    
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time:  15.014 s
    [INFO] Finished at: 2019-07-14T20:41:48-05:00
    [INFO] ------------------------------------------------------------------------

    4.2 InputStreamReaderAppTest

    In this step, I will create two test methods:

    • test_file_as_in – resets System.in from a file
    • test_file_as_in_out – resets System.in and System.out from files

    InputStreamReaderAppTest.java

    package jcg.zheng.demo;
    
    import static org.junit.Assert.assertEquals;
    
    import java.io.FileNotFoundException;
    
    import org.junit.Test;
    
    public class InputStreamReaderAppTest {
    
    	InputStreamReaderApp inputStreamReaderApp = new InputStreamReaderApp();
    
    	@Test
    	public void test_file_as_in() {
    		try {
    			InputStreamHelper.setIn_from_FileInputStream("data/in_file.txt");
    			String data = inputStreamReaderApp.read_in_write_out_and_log_error();
    			assertEquals(" 345", data);
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		}
    	}
    
    	@Test
    	public void test_file_as_in_out() {
    		try {
    			InputStreamHelper.setIn_from_FileInputStream("data/in_file.txt");
    			PrintStreamHelper.setOut_from_OutStream("data/testFile.bin");
    			String data = inputStreamReaderApp.read_in_write_out_and_log_error();
    			assertEquals(" 345", data);
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Execute mvn test -Dtest=InputStreamReaderAppTest and capture the output.

    Output

    C:MaryZhengWorkspacesjdk12java-system-in-out-error-demo>mvn test -Dtest=InputStreamReaderAppTest
    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------< jcg.zheng.demo:java-system-in-out-error-demo >------------
    [INFO] Building java-system-in-out-error-demo 0.0.1-SNAPSHOT
    [INFO] --------------------------------[ jar ]---------------------------------
    [INFO]
    [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-system-in-out-error-demo ---
    [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] skip non existing resourceDirectory C:MaryZhengWorkspacesjdk12java-system-in-out-error-demosrcmainresources
    [INFO]
    [INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ java-system-in-out-error-demo ---
    [INFO] Changes detected - recompiling the module!
    [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
    [INFO] Compiling 6 source files to C:MaryZhengWorkspacesjdk12java-system-in-out-error-demotargetclasses
    [INFO]
    [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ java-system-in-out-error-demo ---
    [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] skip non existing resourceDirectory C:MaryZhengWorkspacesjdk12java-system-in-out-error-demosrctestresources
    [INFO]
    [INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ java-system-in-out-error-demo ---
    [INFO] Changes detected - recompiling the module!
    [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
    [INFO] Compiling 2 source files to C:MaryZhengWorkspacesjdk12java-system-in-out-error-demotargettest-classes
    [INFO]
    [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ java-system-in-out-error-demo ---
    [INFO] Surefire report directory: C:MaryZhengWorkspacesjdk12java-system-in-out-error-demotargetsurefire-reports
    
    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running jcg.zheng.demo.InputStreamReaderAppTest
    Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.182 sec
    
    Results :
    
    Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
    
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time:  11.763 s
    [INFO] Finished at: 2019-07-14T20:39:30-05:00
    [INFO] ------------------------------------------------------------------------

    5. Eclipse System Setting

    As you can see, Java System class provides setIn, setOut, and setErr to use other InputStream and PrintStream. Eclipse IDE provides a convenient UI to redirect them. I will demonstrate with the ScannerApp class created at step 3.4.

    Right click on ScannerApp, select Run As ->Run Configuration.

    Click on the Common tab, enter the Output File as “SystemOutFile.txt”.

    Java System.in System.out System.error - Eclipse Common Setting
    Figure 1 Eclipse Common Setting for Standard Input and Output

    Click the Apply button and then click the "Run" button.

    Capture the Eclipse console output.

    Eclipse Console

    [Console output redirected to file:C:MaryZhengDevToolsEclipseeclipse644.11eclipseSystemOutFile.txt]
    Enter anything from the keyboard:
    test
    Value from System.in:test
    Caught NumberFormatException For input string: "test"
    12
    Value from System.in:12
    q
    Value from System.in:q
    Bye!
    

    View the output file content.

    SystemOutFile.txt

    Enter anything from the keyboard:
    Value from System.in:test
    Caught NumberFormatException For input string: "test"
    Value from System.in:12
    Value from System.in:q
    Bye!

    6. Java System.in System.out System.err – Summary

    In this example, I demonstrated how to read the data from System.in, write the outputs to System.out, and write the error outputs to System.err. I also demonstrated how to reassign System.in to different InputStream classes and reassign System.out to a different PrintStream.

    7. Download the Source Code

    This example consists of a Maven project which deals with System.in, System.out, and System.err.

    System предоставляет нам множество методов, которые помогут нам в таких вещах, как:

    • Доступ к консоли

    • Копирование массивов

    • Наблюдение за датой и временем

    • Выход из JRE

    • Доступ к свойствам во время выполнения

    • Доступ к переменным среды и

    • Администрирование сборки мусора

    3.1. Доступ к консоли

    Java 1.6 представила другой способ взаимодействия с консолью, чем просто использованиеSystem.out иin напрямую.

    Мы можем получить к нему доступ, вызвавSystem.console:

    public String readUsername() {
        Console console = System.console();
    
        return console == null ? null :
          console.readLine("%s", "Enter your name: ");
    }

    Обратите внимание, что в зависимости от базовой операционной системы и того, как мы запускаем Java для запуска текущей программы,console might return null, so always make sure to check before using.

    Ознакомьтесь с документациейConsole для других целей.

    3.2. Копирование массивов

    System.arraycopy — это старый способ копирования одного массива в другой в стиле C.

    В основномarraycopy предназначен для копирования одного полного массива в другой массив:

    int[] a = {34, 22, 44, 2, 55, 3};
    int[] b = new int[a.length];
    
    System.arraycopy(a, 0, b, 0, a.length);
    assertArrayEquals(a, b);

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

    Например, предположим, что мы хотим скопировать 2 элемента изa, начиная сa[1] доb, начиная сb[3]:

    System.arraycopy(a, 1, b, 3, 2);
    assertArrayEquals(new int[] {0, 0, 0, 22, 44, 0}, b);

    Также помните, чтоarraycopy выдаст:

    • NullPointerException, если любой из массивовnull

    • IndexOutOfBoundsException, если копия ссылается на любой массив за пределами своего диапазона

    • ArrayStoreException, если копия приводит к несоответствию типов

    3.3. Наблюдение за датой и временем

    Есть два метода, связанных со временем вSystemс. Один —currentTimeMillis, другой —nanoTime.

    currentTimeMillis возвращает количество миллисекунд, прошедших с Unix Epoch, то есть 1 января 1970 г., 12:00 AM UTC:

    public long nowPlusOneHour() {
        return System.currentTimeMillis() + 3600 * 1000L;
    }
    
    public String nowPrettyPrinted() {
        return new Date(System.currentTimeMillis()).toString();
    }

    nanoTime возвращает время относительно запуска JVM. Мы можем назвать это несколько раз, чтобы отметить ход времени в приложении:

    long startTime = System.nanoTime();
    // ...
    long endTime = System.nanoTime();
    
    assertTrue(endTime - startTime < 10000);

    Обратите внимание, что посколькуnanoTime очень мелкозернистый,it’s safer to do endTime – startTime < 10000 than endTime < startTime due to the possibility of numerical overflow.

    3.4. Выход из программы

    Если мы хотим программно выйти из выполняемой в данный момент программы,System.exit сделает свое дело.

    Чтобы вызватьexit, нам нужно указать код выхода, который будет отправлен в консоль или оболочку, запустившую программу.

    По соглашению в Unix состояние 0 означает нормальный выход, а ненулевое означает, что произошла ошибка:

    if (error) {
        System.exit(1);
    } else {
        System.exit(0);
    }

    Обратите внимание, что для большинства современных программ было бы странно называть это. When called in a web server application, for example, it may take down the entire site!с

    3.5. Доступ к свойствам среды выполнения

    System обеспечивает доступ к свойствам времени выполнения с помощьюgetProperty.

    И мы можем управлять ими с помощьюsetProperty иclearProperty:

    public String getJavaVMVendor() {
        System.getProperty("java.vm.vendor");
    }
    
    System.setProperty("abckey", "abcvaluefoo");
    assertEquals("abcvaluefoo", System.getProperty("abckey"));
    
    System.clearProperty("abckey");
    assertNull(System.getProperty("abckey"));

    Свойства, указанные через-D, доступны черезgetProperty.

    Мы также можем предоставить значение по умолчанию:

    System.clearProperty("dbHost");
    String myKey = System.getProperty("dbHost", "db.host.com");
    assertEquals("db.host.com", myKey);

    АSystem.getProperties предоставляет набор всех системных свойств:

    Properties properties = System.getProperties();

    Из которого мы можем выполнять любые операцииProperties:

    public void clearAllProperties() {
        System.getProperties().clear();
    }

    3.6. Доступ к переменным среды

    System также предоставляет доступ только для чтения к переменным среды с помощьюgetenv.

    Например, если мы хотим получить доступ к переменной окруженияPATH, мы можем:

    public String getPath() {
        return System.getenv("PATH");
    }

    3.7. Администрирование сборки мусора

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

    System.runFinalization — это метод, который позволяет нам предложить JVM запустить процедуру финализации.

    System.gc — это метод, который позволяет нам предложить JVM запустить свою процедуру сборки мусора.

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

    Однако их можно использовать для оптимизации, скажем, для вызоваgc, когда настольное приложение свернуто:

    public void windowStateChanged(WindowEvent event) {
        if ( event == WindowEvent.WINDOW_DEACTIVATED ) {
            System.gc(); // if it ends up running, great!
        }
    }

    Для получения дополнительной информации о завершении ознакомьтесь с нашимfinalize guide.

    Article updated on

    Sunday, 21 April 2013

    In java the three main Streams stdin (standard input) , stdout (standard output) and stderr (standard output error) are handled by default by System.in, Sytem.out and System.err respectively. Sometimes we may need to change the output according to our needs, this can be done in many ways such us using the OS to tell what stream we need to use or using java to set what streams we want to be used.

    In these examples is shown how to deal with these streams in different sceenarios.

    Redirecting streams to file from console in Unix

    java MyExample > output.log 2>error.log

    Redirecting Output Streams to Files

    This example redirects both output streams to 2 different files. It produces an ArithmeticException dividing by 0 and the error trace will be stored in the stderr.log. The results won’t be shown in the console.

    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    public class OutPuts {
        public static void main(String[] args) {
            try {
                FileOutputStream fout = new FileOutputStream("stdout.log");
                FileOutputStream ferr = new FileOutputStream("stderr.log");
                PrintStream out = new PrintStream(fout);
                PrintStream err = new PrintStream(ferr);
                System.setOut(out);
                System.setErr(err);            
                out.println("trace console 1");            
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
            System.out.println("trace console 2");
            System.out.println(100/0);
        }
    
    }

    Redirecting Output Error Stream to the Standard Out Stream.

    public class OutPuts {
        public static void main(String[] args) {    
            System.setErr(System.out);
            System.out.println("trace console");
            System.out.println(100/0);
        }
    }

    Redirecting Output Streams to Files and Printing the result in the console.

    In this example a «proxy» class I used, so that every time the print or println methods are called its output will be printed by the console and also stored the specified files.

    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    public class OutPuts {
        public static void main(String[] args) {
            System.setOut(new ProxyPrintStream(System.out, "stdout.log"));
            System.setErr(new ProxyPrintStream(System.err, "stderr.log"));        
            System.out.println("trace console 1");
            System.out.println(100 / 0);
        }
    }
    class ProxyPrintStream extends PrintStream{    
        private PrintStream fileStream = null;
        private PrintStream originalPrintStream = null;
        public ProxyPrintStream(PrintStream out, String FilePath) {
            super(out);
            originalPrintStream = out;
             try {
                 FileOutputStream fout = new FileOutputStream(FilePath,true);
                 fileStream = new PrintStream(fout);
            } catch (FileNotFoundException e) {
                    e.printStackTrace();
            }
        }    
        public void print(final String str) {
            originalPrintStream.print(str);
            fileStream.print(str);
        }
        public void println(final String str) {
            originalPrintStream.println(str);
            fileStream.println(str);
        }        
    }

    * This example appends traces to the existing file change new FileOutputStream(FilePath,true) for new FileOutputStream(FilePath) to create a new file each time.

    Redirecting Output Streams in Log4J

    This example prints all the traces ment for the standard outputs to the LOG4J files, so you can make sure that all traces are there.

        /**
         * To change tie the sysOut and sysErr to the log
         */
        public static void tieSystemOutAndErrToLog() {
            System.setOut(createLoggingProxy(System.out));
            System.setErr(createLoggingProxy(System.err));
        }
        public static PrintStream createLoggingProxy(final PrintStream realPrintStream) {
            return new PrintStream(realPrintStream) {
                public void print(final String string) {
                    logger.warn(string);
                }
                public void println(final String string) {
                    logger.warn(string);
                }
            };
        }

    Содержание

    1. Class System
    2. Nested Class Summary
    3. Field Summary
    4. Method Summary
    5. Methods declared in class java.lang.Object
    6. Field Details
    7. Method Details
    8. setIn
    9. setOut
    10. setErr
    11. console
    12. inheritedChannel
    13. setSecurityManager
    14. getSecurityManager
    15. currentTimeMillis
    16. nanoTime
    17. arraycopy
    18. identityHashCode
    19. getProperties
    20. lineSeparator
    21. setProperties
    22. getProperty
    23. getProperty
    24. setProperty
    25. clearProperty
    26. getenv
    27. getenv
    28. getLogger
    29. getLogger
    30. runFinalization
    31. loadLibrary
    32. mapLibraryName

    Class System

    Nested Class Summary

    Nested Classes

    Field Summary

    Modifier and Type Class Description
    static interface System.Logger

    Method Summary

    Modifier and Type Field Description
    static PrintStream err

    Fields

    Methods declared in class java.lang.Object

    Field Details

    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 Details

    setIn

    setOut

    setErr

    console

    inheritedChannel

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

    setSecurityManager

    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 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.

    Otherwise, if any of the following is true, an ArrayStoreException is thrown and the destination 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.

    Otherwise, if any of the following is true, an IndexOutOfBoundsException is thrown and the destination is not modified:

    • 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

    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 includes a value for each of the following keys unless the description of the associated value indicates that the value is optional.

    Modifier and Type Method Description
    static void arraycopy ​(Object src, int srcPos, Object dest, int destPos, int length)
    Key Description of Associated Value
    java.version Java Runtime Environment version, which may be interpreted as a Runtime.Version
    java.version.date Java Runtime Environment version date, in ISO-8601 YYYY-MM-DD format, which may be interpreted as a LocalDate
    java.vendor Java Runtime Environment vendor
    java.vendor.url Java vendor URL
    java.vendor.version Java vendor version (optional)
    java.home Java installation directory
    java.vm.specification.version Java Virtual Machine specification version, whose value is the feature element of the 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, whose value is the feature element of the 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 (refer to ClassLoader.getSystemClassLoader() for details)
    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

    Shows property keys and associated values

    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.

    API Note: Changing a standard system property may have unpredictable results unless otherwise specified. Property values may be cached during initialization or on first use. Setting a standard property after initialization using getProperties() , setProperties(Properties) , setProperty(String, String) , or clearProperty(String) may not have the desired effect. Implementation Note: In addition to the standard system properties, the system properties may include the following keys:

    Shows property keys and associated values

    Key Description of Associated Value
    jdk.module.path The application module path
    jdk.module.upgrade.path The upgrade module path
    jdk.module.main The module name of the initial/main module
    jdk.module.main.class The main class name of the initial module

    Returns: the system properties Throws: SecurityException — if a security manager exists and its checkPropertiesAccess method doesn’t allow access to the system properties. See Also: setProperties(java.util.Properties) , SecurityException , SecurityManager.checkPropertiesAccess() , Properties

    lineSeparator

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

    setProperties

    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

    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

    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

    clearProperty

    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 reuse by the Java Virtual Machine. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all unused objects. There is no guarantee that this effort will recycle any particular number of unused objects, reclaim any particular amount of space, or complete at any particular time, if at all, before the method returns or ever.

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

    runFinalization

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

    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, 2020, 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 syntax error on token delete this token
  • Java sql sqlrecoverableexception io error the network adapter could not establish the connection
  • Java sql sqlrecoverableexception io error socket read interrupted
  • Java sql sqlrecoverableexception io error got minus one from a read call
  • Java sql sqlexception network error ioexception socket failed eacces permission denied