Java I/O Stream operations (I)-Introduction to the system and properties classes

Source: Internet
Author: User
  System and properties:This article mainly introduces the usage of the system class. You can learn about the usage of the system class in detail through Java API: the API documentation gives us the best helper to learn: the system is final, so we can see that it is not allowed to be modified by others. If it is not final, the extends can be used to override the method.

The following is a brief introduction to the above Java API fragment. This system class contains some useful service class fields and methods. It cannot be instantiated, that is, its constructor is private, the system class provides some standard output input streams and error output streams,

The copy array method is also provided, for example:

The following describes the above functions for specific applications: Output Environment Variable Properties = system. getproperties ();
// Obtain all system environment variables
For (Object key: properties. keyset ()){
String value = (string) properties. Get (key );
System. Out. println (Key + "--->" + value );
}
// Obtain a system environment variable
String value = properties. getproperty ("Java. VM. Version ");
System. Out. println (value );

// Customize some system environment variables
Properties. setproperty ("mypro", "My System Properties ");
System. Out. println (properties. getproperty ("mypro"); for example: public class testsystem
{
Public static void main (string [] ARGs) throws exception
{
// Obtain all environment variables of the system
Map <string, string> Env = system. getenv ();
For (string name: ENV. keyset ())
{
System. Out. println (name + "------>" + env. Get (name ));
}
// Obtain the value of the specified environment variable
System. Out. println (system. getenv ("java_home "));
// Obtain all system attributes
Properties props = system. getproperties ();
// Save all system tokens to the props.txt File
Props. Store (New fileoutputstream ("props.txt"), "System Properties ");
// Output specific system attributes
System. Out. println (system. getproperty ("OS. Name "));
}
}

Runtime class: runtime indicates that the Java program runs in an environment. Each Java program has a corresponding runtime instance, and the application is connected to the runtime environment through this object. as described in the API documentation.

It can be learned that this class cannot be directly instantiated, but the instance can be obtained through the getrumtime method, this is obviously Singleton mode. Since a Java program corresponds to a runtime, only one runtime exists in a Java program, so it is Singleton. you can obtain some common methods by viewing the API: public class testruntime.
{
Public static void main (string [] ARGs)
{
Runtime RT = runtime. getruntime ();
System. Out. println ("Number of processors:" + RT. availableprocessors ());
System. Out. println ("Idle memory:" + RT. freememory ());
System. Out. println ("total memory:" + RT. totalmemory ());
System. Out. println ("maximum available memory:" + RT. maxmemory ());
}
} You can also open the program public class testexec
{
Public static void main (string [] ARGs) throws exception
{
Runtime RT = runtime. getruntime ();
PROCESS p = rt.exe C ("notepad.exe"); // P. Destroy (); close the process
}
And you can open a specific file such as rt.exe C ("notepad.exe systemtest. Java ");

Basic Io operation: stream classification: input stream: Only data can be read from it, mainly using inputstream and reader as the base class. Output stream: Only data can be written to it. outputstream and writer are used as the base class. The byte stream operation method is almost the same as the byte stream operation method. The difference is only the difference between data units. The byte stream operation unit is byte, And the byte stream operation unit is character. Input/output stream system:

First, let's take a look at filewriter as a character output stream. filewriter fw = new filewriter ("test.txt"); // specifies the file for output stream operations. When we write data to this file, Fw. writer ("test"); the running can still have no data in the file, but we have clearly written it because the data we write is still in the memory and not written to the disk, we need to use FW. the flush method refreshes the data in the memory to the target, or uses the close method, because the close method also calls the flush method before calling the close method. note that if the specified file already exists on the disk, the file will be overwritten. public class filewritertest {public static void main (string [] ARGs) throws exception {filewriter fw = new filewriter ("test.txt"); FW. writer ("ASDF"); FW. close () ;}} the above program has one disadvantage: No Io Exception Handling: in the three main lines of code of the main method, may throw an exception, so try catch public class filewritertest {public static void main (string [] ARGs) {try {filewriter fw = new filewriter ("test.txt "); // create the test.txt file in the hosts file. If the file exists, it overwrites the FW file. writer ("ASDF"); FW. close ();} catch (ioexception e) {system. out. println (E. tostring (); // but in actual development, this is not the case but the actual processing} finally {// we know that finally is generally used to close the resource try {FW. close ();} catch (ioexception e ){

System. Out. println (E. tostring}

}}}

However, an error will still be reported during compilation, indicating that the FW variable cannot be found because FW is in the try block. Why can't FW be found in try block? Because in filewriter fw = new filewriter ("test.txt"); there may be code before the Code. If the code reports an exception, the filewriter fw = new filewriter ("test.txt") cannot be executed "); so filwwriter must be defined before try.
We should also note that, in order to ensure the robustness of the program, we should judge that the value is null when the resources are closed, so here we can sum up that we should pay attention to calling a method, first, we need to consider whether the method caller exists. If this method has parameters, we need to determine whether the parameters exist. Pay attention to these two points during programming. the robustness of programs that can be increased. do not throw an exception if the program does not move. in fact, the exception mechanism exists to make the program more robust. we know that the above program cannot implement the continued file writing, because if the file exists, it will be overwritten. How can we implement the continued file writing? View API documentation:

A boolean parameter indicates whether to append an existing file. Public static voidMain (string [] ARGs) {filewriter fw = Null; Try{Fw = NewFilewriter ("test.txt ", True); FW. Write ("Hello! ");} Catch(Ioexception e) {e. printstacktrace ();} Finally{ Try{ If(FW! = Null) {FW. Close ();}} Catch(Exception E2) {e2.printstacktrace ();}

} File content before execution:

Filereader class for File Reading

From the above API, we can see that when the file is read, it will return-1 and its return value is int. If the characters in the text file need to be converted to Char by Baint. in this way, we have a loop condition. This class is very simple. It seems that APIs can be used. here we will not give an example. file Reading Method

The two read methods above, although their return values are equal, have different meanings. The read () method without parameters is to read a single character and return the int form of the content, the read () method with parameters is to put the read content into the character array. returns the number of reads.

If the length of the character array is not long enough, use the box number instead. If the program is changed, this will not happen. Fr = new filereader ("test.txt "); char [] buffer = new char [10]; int length = 0; while (length = Fr. read (buffer ))! =-1) {system. Out. println ("length =" + Length + "--- content =" + new string (buffer, 0, length ));

} Indicates how long it will take to read the file. This will help you understand why you need to write the copy file program like this.

Byte [] buffer = new byte [1024];

Int length = 0;

While (length = is. Read (buffer ))! =-1 ){

OS. Write (buffer, 0, length );

}

 

Reprinted please indicate the source:
Http://blog.csdn.net/johnny901114/article/details/8710381

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.