1.04k likes | 1.06k Views
Explore the System class for system resource usage and formatting methods in JDK 1.5, including input/output streams, Scanner, Formatter, and more. Learn about the Runtime object, System.out.Println, and standard I/O streams.
E N D
Programming in Java I/O Stream 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw http://www.csie.nctu.edu.tw/~tsaiwn/java/
Outline • the System class • System Properties • Miscellaneous System Methods • Input / Output Stream • Byte Stream vs. Character Stream • Character Stream family • Byte Stream family • Data Sink Stream • Processing Stream • Random Access File • Other Input/Output Streams
New Features in JDK 1.5 (JDK5.0) • Scanner and Formatter • simplified input and formatted output • java.util.Scanner • printf ( java.util.Formatter ) • Autoboxing • Automatic wrapping and unwrapping of primitives • Enumerated Types • Provides benefits of the Typesafe Enum pattern • Foreach loop • Generic Types (template) • Compile-time type safety for collections without casting
The System Class • java.lang.System class allows your Java programs to use system resources but insulates them from system-specific details.
The Runtime Object (1/2) • The oval labeled Runtime represents the current runtime environment. • An instance of the Runtime class.
The Runtime Object (2/2) • Runtimeobjects provide two services. • They communicate with the components of the runtime environment. • Getting information and invoking functions. • Runtime objects are also the interface to system-dependent capabilities. • For example, UNIXRuntime objects might support the getenv and setenv functions. Other Runtime objects, such as for Mac OS, might not support.
Different from in C++ Using the java.lang.System Class • You do not instantiate the System class to use it. • All of System's variables and methods are class variables and class methods. • They are declared static. • To use a class variable, you use it directly from the name of the class using Java's dot (.) notation. class UserNameTest { public static void main(String[] args) { String name; name = System.getProperty("user.name"); System.out.println(“Your name is “ + name); } } • Notice that the program never instantiates a System object. It just references the getProperty method and the out variable directly from the class.
System.out.println(…) ? • System.out is an object that is part of the Java language • println is a method invoked by the System.outobject that can be used for console output • The data to be output is given as an argument in parentheses • A plus sign is used to connect more than one item • Every invocation of println ends a line of output System.out.println("The answer is " + 42);
The Standard I/O Streams • Standard Input Stream • The System class provides a stream for reading text -- the standard input stream. • Referenced by System.in • Use System.in.read to read the input entered by user. • Standard Output and Error Streams • The standard output stream is typically used for command output. • Referenced by System.out • The standard error stream is typically used to display any errors that occur when a program is running. • Referenced by System.err • The print, println, and write Methods • The print and println methods write their String argument to the stream. System.out.println("Duke is not a penguin!"); • The write method is used to write bytes to the stream. Use write to write non-ASCII data.
Arguments to print and println • print and println methods both take a single argument: Object, String, char[], int, long, float, double, and boolean. • println takes no arguments and just prints a newline to the stream. public class DataTypePrintTest { public static void main(String[] args) { Thread objectData = new Thread(); String stringData = "Java Mania"; char[] charArrayData = { 'a', 'b', 'c' }; int integerData = 4; long longData = Long.MIN_VALUE; float floatData = Float.MAX_VALUE; double doubleData = Math.PI; boolean booleanData = true; System.out.println(objectData); System.out.println(stringData); System.out.println(charArrayData); System.out.println(integerData); System.out.println(longData); System.out.println(floatData); System.out.println(doubleData); System.out.println(booleanData); System.out.println(); } }
Output Thread[Thread-4,5,main] Java Mania abc 4 -9223372036854775808 3.40282e+38 3.14159 true
Formatting Output • Before JDK 1.5: • The java.text.NumberFormat class allows you to format values as currency or percentages • The java.text.DecimalFormat class allows you to format values based on a pattern • JDK 1.5 (5.0) and later: • Java.util.Scanner • You can also use printf function which similar to the printf function in C language
java.text.DecimalFormat • See examples in previous slides • java.text.NumberFormat, java.text.DecimalFormat • format function, format pattern • parse function
Method Detail in DecimalFormat format public StringBufferformat(doublenumber, StringBufferresult, FieldPositionfieldPosition) Description copied from class: NumberFormat Specialization of format. Overrides: format in class NumberFormat Tags copied from class: NumberFormat See Also: Format.format(java.lang.Object)
Formatting Output with printf • Starting with version 1.5 (5.0), Java includes a method named printf that can be used to produce output in a specific format • The Java method printf is similar to the print method • Like print, printf does not advance the output to the next line • System.out.printfcan have any number of arguments • The first argument is always a format string that contains one or more format specifiers for the remaining arguments • All the arguments except the first are values to be output to the screen
C Style Output (1/5) • Java 5.0 在java.util.Formatter類別中開始支援C-Style (C風格)的輸出,除了使用屬於Formatter類別的物件配合System.out.println( )方法輸出之外,還可以直接使用類似C語言printf函數的System.out.printf()方法。 System.out.printf(”控制字串”, 運算式1, 運算式2, ...); • 控制字串中可以包含許多以百分比符號(%)引導的控制符號,see next slide:
C Style Output (3/5) • 在上表中的大部份控制字符前,還可以加上如下所列的旗號(flag):
C Style Output (4/5) • 我們使用以下的程式片段來說明System.out.printf( )用法: System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3); System.out.printf("%.4f", 123.1234567); System.out.printf("%16.2e", 123.1234567); System.out.printf("% ,.2f\n% ,.2f\n", 1234567.123, -1234567.123); System.out.printf("|%f|%n|%12f|%n|%012f|",10.12345, 10.12345, 10.12345); System.out.printf(“%9s”,“C風格的輸出功能很好用");
C風格的輸出 (5/5) • 上述的程式片段輸出的結果為: 3 (3) +3 00003 123.1235 1.23e+02 1,234,567.12 -1,234,567.12 |10.123450| | 10.123450| |00010.123450| C風格的輸出功能很 注意答案
More about printf method • In addition, some Java classes like Date and BigInteger also have their formatting rules. • Handles • java.util.Date • numeric types • native types • strings • See the java.util.Formatter class for more information.
java.util.Scanner -- JDK1.5 (5.0) • Finally, Java has a fairly simple way to read input • Scanner sc = Scanner.create(System.in); • boolean b = sc.nextBoolean( ); • byte by = sc.nextByte( ); • short sh = sc.nextShort( ); • int i = sc.nextInt( ); • long l = sc.nextLong( ); • float f = sc.nextFloat( ); • double d = sc.nextDouble( ); • String s = sc.nextLine( ); • By default, whitespace acts as a delimiter, but you can define other delimiters with regular expressions.
Testing Methods in java.util.Scanner boolean hasNext() boolean hasNext( Pattern ptrn ) boolean hasNextBoolean() boolean hasNextDouble() boolean hasNextInt() boolean hasNextInt( int radix ) boolean hasNextLine()
using java.util.Scanner Scanner stdin = Scanner.create(System.in); int n = stdin.nextInt(); String s = stdin.next(); boolean b = stdin.hasNextInt()
格式化的輸入 (1/3) • 除了nextInt( )方法之外,Scanner還提供許多其他的方法以方便使用者進行輸入操作,以下我們一一介紹:
JDK1.5 (5.0) Autoboxing/Unboxing • Wrap ints into Integers • Extract ints from Integers This is now legal: Integer x = 6; //6 is boxed Integer y = 2*x + 3; //x is unboxed, then the answer 15 is boxed You could hide primitives entirely!
Enumerations (JDK1.5) • An enumeration, or “enum,” is simply a set of constants to represent various values. • Here’s the old way of doing it: • public final int SPRING = 0;public final int SUMMER = 1;public final int FALL = 2;public final int WINTER = 3; • This is a nuisance, and is error prone as well. • Here’s the new way of doing it: • enum Season {SPRING, SUMMER, FALL, WINTER }
Enumeration Type Issues • Are they just integers? • Type safety • How are they input and output? • Brittleness in the face of changes • Can they be treated like classes? • Methods • Extensions • Name clashes?
enums are classes • An enum is actually a new type of class. • You can declare them as inner classes or outer classes. • You can declare variables of an enum type. • Each declared value is an instance of the enum class. • Enums are implicitlypublic, static, and final. • enums extend java.lang.Enum and implement java.lang.Comparable. • Supports equals, “==”, compareTo, ordinal, etc. • Enums override toString() and provide valueOf(…), name(). • Example: • Season season = Season.WINTER; • System.out.println(season ); // prints WINTER • season = Season.valueOf("SPRING"); // sets season to Season.SPRING
Advantages of the new enum • Enums provide compile-time type safety. • int enums don't provide any type safety at all: season = 43; • Enums provide a proper name space for the enumerated type. • With int enums you have to prefix the constants (for example, seasonWINTER or S_WINTER) to get anything like a name space. • Enums are robust. • If you add, remove, or reorder constants, you must recompile, and then everything is OK again. • Enum printed values are informative. • If you print an int enum you just see a number • Because enums are objects, you can put them in collections. • Because enums are classes, you can add fields and methods.
Enums really areclasses • public enum Coin { • // enums can have instance variablesprivate final int value; • // An enum can have a constructor, but it isn’t publicCoin(int value) { this.value = value; } • // Each enum value you list really calls a constructor PENNY(1), NICKEL(5), DIME(10), QUARTER(25); • // And, of course, classes can have methodspublic int value( ) { return value; }public static void main( String[] args ) { int sum = 0; for ( String arg: args ) sum += Coin.valueOf( arg ).value(); System.out.println( sum + " cents" ); } • }
Other features of enums • values() returns an array of enum values. • Season[] seasonValues = Season.values(); • switch statements can now work with enums. • switch (thisSeason) { case SUMMER: ...; default: ...} • You must say case SUMMER:, notcase Season.SUMMER: • It’s still a very good idea to include a default case.
Enum Semantics • Only one copy of each value (instance) of an Enum class is allowed. • The operator == works fine. • No new instances allowed. • No public constructors allowed. • No subclasses allowed (messy semantics). • Each instance must be created. • Static initializers cannot refer to the instances.
Useful enum Collection Classes • Optimized for enumerations: • EnumSet • Uses a bit set implementation. • EnumMap • Used to store additional information for each enum literal. • Often declared inside the enum itself.
Persistence Properties • enums implement Serializable. • Their serialized form as a byte array does not change even if the list of literals is modified. • This means that data in a file does not become obsolete, and network peers can be at different revision levels. • Robust in the face of modifications.
Static import facility • import static org.iso.Physics.*;class Guacamole { public static void main(String[] args) { double molecules = AVOGADROS_NUMBER * moles; ... }} • You no longer have to say Physics.AVOGADROS_NUMBER. • Are you tired of typing System.out.println(something); ? • Do this instead: • import static java.lang.System.out; • out.println(something);
Prototype of the System Class Peruse of the javap
Reading System Properties • Reading System Properties • The System class has two methods to read the system properties: getProperty and getProperties. • The simpler version of getProperty : System.getProperty("path.separator"); • Another version requires two String arguments: • First argument is the key to look up. • The second argument is a default value to return if the key cannot be found or if it has no value. System.getProperty("subliminal.message", "Buy Java Now!"); • The getProperties method returns a Properties object. • Use the various Properties class methods to query the Properties objects for specific values or to list the entire set of properties.
Writing System Properties • Writing System Properties • System's setProperties method takes a Properties object that has been initialized to contain the key/value pairs for the properties that you want to set. • Example: myProperties.txt : subliminal.message=Buy Java Now! • Changing the system properties within an application will not effect future invocations of the Java interpreter for this or any other application. java.vendor=Acme Software Company
import java.io.FileInputStream; import java.util.Properties; public class PropertiesTest { public static void main(String[] args) throws Exception { // set up new properties object // from file "myProperties.txt” FileInputStream propFile = new FileInputStream("myProperties.txt"); Properties p = new Properties(System.getProperties()); p.load(propFile); // set the system properties System.setProperties(p); // display new properties System.getProperties().list(System.out); } }
Forcing Finalization and Garbage Collection • Finalizing Objects • Before an object is garbage collected, the Java runtime system gives the object a chance to clean up after itself. • You can force object finalization to occur by calling System's runFinalization method. System.runFinalization(); • Running the Garbage Collector • Ask the garbage collector to run at any time by calling System's gc method: System.gc(); • Running the garbage collector to ensure that it runs at the best time for your program. • Rather than when it's most convenient for the runtime system to run it.
Providing Your Own Security Manager • The SecurityManager class in the java.lang package is an abstract class. • Providing the programming interface and partial implementation for all Java security managers. • Get the current security manager • Using the System class's getSecurityManager() method: SecurityManager appsm = System.getSecurityManager(); • Once you have the security manager, you can request permission to allow or disallow certain operations. SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkExit(status); } . . . // code continues here if checkedExit() returns • If the security manager approves the exit operation, the checkExit() returns normally. • If the security manager disallows the operation, the checkExit() method throws a SecurityException.
Writing a Security Manager (1/3) • Writing a Security Manager • An security manager example that restricts reading and writing to the file system. • This example prompts the user for a password. • When the application attempts to open a file for reading or for writing. • All security managers must be a subclass of SecurityManager. class PasswordSecurityManager extends SecurityManager { . . . } • PasswordSecurityManager declares a private instance variable password to contain the password that the user must enter in order to allow the restricted file system accesses. PasswordSecurityManager(String password) { super(); this.password = password; }
Writing a Security Manager (2/3) • The SecurityManager’s accessOK()method prompts the user for a password and verifies it. private boolean accessOK() { int c; DataInputStream dis = new DataInputStream(System.in); String response; System.out.println("What's the secret password?"); try { response = dis.readLine(); if (response.equals(password)) return true; else return false; } catch (IOException e) { return false; }
Writing a Security Manager (3/3) • three overridden checkRead() methods and the two overridden checkWrite() methods: public void checkRead(FileDescriptor filedescriptor) { if (!accessOK()) throw new SecurityException("Not a Chance!"); } public void checkRead(String filename) { if (!accessOK()) throw new SecurityException("No Way!"); } public void checkRead(String filename, Object executionContext) { if (!accessOK()) throw new SecurityException("Forget It!"); } public void checkWrite(FileDescriptor filedescriptor) { if (!accessOK()) throw new SecurityException("Not!"); } public void checkWrite(String filename) { if (!accessOK()) throw new SecurityException("Not Even!"); }
Implementing a Security Manager • Implementing a SecurityManager is simple. • Create a SecurityManager subclass. • Override a few methods. • The tricky part is determining which methods to override and implementing your security policy. • Installing Your Security Manager • Installing your security manager as the current one for Java application with the setSecurityManager() method from the System class. try { System.setSecurityManager(new PasswordSecurityManager("Booga Booga")); } catch (SecurityException se) { System.out.println("SecurityManager already set!"); } • You can set the security manager for your application only once. • Browser sets its security manager during its startup procedure. • So most of the time, applets cannot set the security manager because it's already been set.