交通大學資訊工程學系 programming in java i/o stream 蔡文能...
Post on 22-Dec-2015
314 views
TRANSCRIPT
交通大學資訊工程學系
Programming in Java
I/O Stream
蔡文能交通大學資訊工程學系[email protected]
http://www.csie.nctu.edu.tw/~tsaiwn/java/
交通大學資訊工程學系 蔡文能 io-第 2頁
Java Java Input/Output
Outline
the System classSystem PropertiesMiscellaneous System MethodsInput / Output StreamByte Stream vs. Character StreamCharacter Stream familyByte Stream familyData Sink StreamProcessing StreamRandom Access FileOther Input/Output Streams
交通大學資訊工程學系 蔡文能 io-第 3頁
Java Java Input/Output
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 loopGeneric Types (template) Compile-time type safety for collections without casting
交通大學資訊工程學系 蔡文能 io-第 4頁
Java Java Input/Output
The System Class
java.lang.System class allows your Java programs to use system resources but insulates them from system-specific details.
交通大學資訊工程學系 蔡文能 io-第 5頁
Java Java Input/Output
The Runtime Object (1/2)
The oval labeled Runtime represents the current runtime environment. An instance of the Runtime class.
交通大學資訊工程學系 蔡文能 io-第 6頁
Java Java Input/Output
Runtime objects 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, UNIX Runtime objects might support the getenv and setenv functions. Other Runtime objects, such as for Mac OS, might not support.
The Runtime Object (2/2)
交通大學資訊工程學系 蔡文能 io-第 7頁
Java Java Input/Output
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.
Different from in C++
交通大學資訊工程學系 蔡文能 io-第 8頁
Java Java Input/Output
System.out.println(…) ?
System.out is an object that is part of the Java languageprintln is a method invoked by the System.out object 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);
交通大學資訊工程學系 蔡文能 io-第 9頁
Java Java Input/Output
The Standard I/O StreamsStandard 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 MethodsThe 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.
交通大學資訊工程學系 蔡文能 io-第 10頁
Java Java Input/Output
Arguments to print and printlnprint 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(); }}
交通大學資訊工程學系 蔡文能 io-第 11頁
Java Java Input/Output
OutputThread[Thread-4,5,main]Java Maniaabc4-92233720368547758083.40282e+383.14159true
交通大學資訊工程學系 蔡文能 io-第 12頁
Java Java Input/Output
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
交通大學資訊工程學系 蔡文能 io-第 13頁
Java Java Input/Output
java.text.DecimalFormat
See examples in previous slides java.text.NumberFormat, java.text.DecimalFormat format function, format pattern parse function
交通大學資訊工程學系 蔡文能 io-第 14頁
Java Java Input/Output
Method Detail in DecimalFormat
format
public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition)
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)
交通大學資訊工程學系 蔡文能 io-第 15頁
Java Java Input/Output
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 formatThe Java method printf is similar to the print method Like print, printf does not advance the output to the next line
System.out.printf can 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
交通大學資訊工程學系 蔡文能 io-第 16頁
Java Java Input/Output
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:
交通大學資訊工程學系 蔡文能 io-第 17頁
Java Java Input/Output
C Style Output (2/5)控制符號 含 意
%% 在字串中顯示%
%d 以 10 進位整數方式輸出
%f 將浮點數以 10 進位方式輸出
%e, %E 將浮點數以 10 進位科學記號方式輸出
%a, %A 使用科學記號輸出浮點數,以 16進位輸出整數部份,以 10 進位輸出指數部份
%o 以 8 進位整數方式輸出
%x, %X 將浮點數以 16 進位方式輸出
%s, %S 輸出格式化字串
%c, %C 以字元方式輸出
%b, %B 輸出布林值 "true"或 "false"(使用%B則輸出 "TRUE" 或 "FALSE")。另外,非 null值輸出是 "true", null值輸出是 "false"
%n 輸出平台相依的換列字元,如果是在Windows 作業系統下實際上會置換為 '/r/n',如果是在Unix作業系統下則會置換為 '/n'
交通大學資訊工程學系 蔡文能 io-第 18頁
Java Java Input/Output
C Style Output (3/5)
在上表中的大部份控制字符前,還可以加上如下所列的旗號 (flag):
特殊旗號 含 意
數字 (d格式等 ) 數字代表輸出的欄位總寬度
數字 1.數字 2(f格式等 )
數字 1代表輸出的欄位總寬度;數字 2代表輸出的小入部份欄位寬度
+ 正數前輸出 +,負數前輸出 -
空白 正數前輸出空白,負數前輸出 -
0 數字前輸出前導 0
- 輸出向左對齊
( 負數以加括號方式輸出
, 數字每隔 3位加一逗點
# (f 格式 ) 永遠加上小數點
# (x 格式 ) 輸出加上 0x字首
# (o 格式 ) 輸出加上 0 字首
交通大學資訊工程學系 蔡文能 io-第 19頁
Java Java Input/Output
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風格的輸出功能很好用 ");
交通大學資訊工程學系 蔡文能 io-第 20頁
Java Java Input/Output
C 風格的輸出 (5/5)
上述的程式片段輸出的結果為:3 (3) +3 00003123.1235 1.23e+02 1,234,567.12-1,234,567.12|10.123450|| 10.123450||00010.123450|C 風格的輸出功能很 注意答案
交通大學資訊工程學系 蔡文能 io-第 21頁
Java Java Input/Output
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.
交通大學資訊工程學系 蔡文能 io-第 22頁
Java Java Input/Output
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.
交通大學資訊工程學系 蔡文能 io-第 23頁
Java Java Input/Output
Testing Methods in java.util.Scanner
boolean hasNext()
boolean hasNext( Pattern ptrn )
boolean hasNextBoolean()
boolean hasNextDouble()
boolean hasNextInt()
boolean hasNextInt( int radix )
boolean hasNextLine()
交通大學資訊工程學系 蔡文能 io-第 24頁
Java Java Input/Output
using java.util.ScannerScanner stdin = Scanner.create(System.in);
int n = stdin.nextInt();
String s = stdin.next();
boolean b = stdin.hasNextInt()
交通大學資訊工程學系 蔡文能 io-第 25頁
Java Java Input/Output
格式化的輸入 (1/3)除了 nextInt( )方法之外, Scanner還提供許多其他的方法以方便
使用者進行輸入操作,以下我們一一介紹:方法名稱 功能
hasNext() 檢查輸入串流中是否仍有待輸入的 token(輸入單元 )
hasNext(String 比對字串 ) 檢查輸入串流中是否仍有待輸入且與比對字串吻合的 token
hasNextBigDecimal() 檢查下一個待輸入的 token是否能夠輸入為 BigDecimal 物件
hasNextBigInteger() 檢查下一個待輸入的 token是否能夠輸入為 BigInteger 物件
hasNextBigInteger(int 基底參數 ) 檢查下一個待輸入的 token是否能夠輸入為以基底參數為基底的 BigInteger 物件
hasNextBoolean() 檢查下一個待輸入的 token是否能夠輸入為以不區別大小寫的 true/false建立的布 林值
hasNextByte() 檢查下一個待輸入的 token 是否能夠輸入為一個位元組值
hasNextByte(int 基底參數 ) 檢查下一個待輸入的 token是否能夠輸入為一個以基底參數為基底的位元組值
hasNextDouble() 檢查下一個待輸入的 token 是否能夠輸入為一個倍精準度浮點數值
hasNextFloat() 檢查下一個待輸入的 token是否能夠輸入為一個浮點數值
hasNextInt() 檢查下一個待輸入的 token 是否能夠輸入為一個整數值
hasNextInt(int 基底參數 ) 檢查下一個待輸入的 token是否能夠輸入為一個以基底參數為基底的整數值
交通大學資訊工程學系 蔡文能 io-第 26頁
Java Java Input/Output
格式化的輸入 (2/3)hasNextLine() 檢查是否仍有一列待輸入的資料
hasNextLong() 檢查下一個待輸入的 token 是否能夠輸入為一個長整數值
hasNextLong(int 基底參數 ) 檢查下一個待輸入的 token是否能夠輸入為一個以基底參數為基底的長整數值
hasNextShort() 檢查下一個待輸入的 token 是否能夠輸入為一個短整數值
hasNextShort(int 基底參數 ) 檢查下一個待輸入的 token是否能夠輸入為一個以基底參數為基底的短整數值
next() 輸入下一個待輸入的 token (以字串傳回 )
next(String 比對字串 ) 輸入下一個待輸入且與比對字串吻合的 token
nextBigDecimal() 將下一個待輸入的 token輸入為 BigDecimal 物件
nextBigInteger() 將下一個待輸入的 token輸入為 BigInteger 物件
nextBigInteger(int 基底參數 ) 將下一個待輸入的 token是輸入為以基底參數為基底的 BigInteger 物 件
nextBoolean() 將下一個待輸入的 token輸入為以不區別大小寫的 true/false建立的布 林值
nextByte() 將下一個待輸入的 token 輸入為一個位元組值
nextByte(int 基底參數 ) 將下一個待輸入的 token輸入為一個以基底參數為基底的位元組值
nextDouble() 將下一個待輸入的 token 輸入為一個倍精準度浮點數值
交通大學資訊工程學系 蔡文能 io-第 27頁
Java Java Input/Output
格式化的輸入 (3/3)nextFloat() 將下一個待輸入的 token輸入為一個浮點數值
nextInt() 將下一個待輸入的 token 輸入為一個整數值
nextInt(int 基底參數 ) 將下一個待輸入的 token輸入為一個以基底參數為基底的整數值
nextLine() 輸入一列資料 (以字串傳回 )
nextLong() 將下一個待輸入的 token 輸入為一個長整數值
nextLong(int 基底參數 ) 將下一個待輸入的 token輸入為一個以基底參數為基底的長整數值
nextShort() 將下一個待輸入的 token 輸入為一個短整數值
nextShort(int 基底參數 ) 將下一個待輸入的 token輸入為一個以基底參數為基底的短整數值
useDelimiter(String 分隔樣板字串 )
設定以分隔樣板字串來作為區隔 token的依據
delimiter() 取得分隔樣版 (以 Pattern物件傳回 )
交通大學資訊工程學系 蔡文能 io-第 28頁
Java Java Input/Output
JDK1.5 (5.0) Autoboxing/UnboxingWrap 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!
交通大學資訊工程學系 蔡文能 io-第 29頁
Java Java Input/Output
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 }
交通大學資訊工程學系 蔡文能 io-第 30頁
Java Java Input/Output
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?
交通大學資訊工程學系 蔡文能 io-第 31頁
Java Java Input/Output
enums are classesAn 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 implicitly public, 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 WINTERseason = Season.valueOf("SPRING"); // sets season to Season.SPRING
交通大學資訊工程學系 蔡文能 io-第 32頁
Java Java Input/Output
Advantages of the new enumEnums 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.
交通大學資訊工程學系 蔡文能 io-第 33頁
Java Java Input/Output
Enums really are classes public enum Coin { // enums can have instance variables
private final int value; // An enum can have a constructor, but it isn’t public
Coin(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 methods
public 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" );
} }
交通大學資訊工程學系 蔡文能 io-第 34頁
Java Java Input/Output
Other features of enumsvalues() 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:,
not case Season.SUMMER: It’s still a very good idea to include a default case.
交通大學資訊工程學系 蔡文能 io-第 35頁
Java Java Input/Output
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.
交通大學資訊工程學系 蔡文能 io-第 36頁
Java Java Input/Output
Useful enum Collection ClassesOptimized for enumerations:
EnumSet Uses a bit set implementation.
EnumMap Used to store additional information for each enum
literal. Often declared inside the enum itself.
交通大學資訊工程學系 蔡文能 io-第 37頁
Java Java Input/Output
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.
交通大學資訊工程學系 蔡文能 io-第 38頁
Java Java Input/Output
Static import facilityimport 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);
交通大學資訊工程學系 蔡文能 io-第 39頁
Java Java Input/Output
java.lang.System
交通大學資訊工程學系 蔡文能 io-第 40頁
Java Java Input/Output
Prototype of the System ClassPeruse of the javap
交通大學資訊工程學系 蔡文能 io-第 41頁
Java Java Input/Output
System PropertiesKey Meaning
"file.separator" File separator (for example, "/")"java.class.path" Java classpath"java.class.version" Java class version number"java.home" Java installation directory"java.vendor" Java vendor-specific string"java.vendor.url" Java vendor URL"java.version" Java version number"line.separator" Line separator"os.arch" Operating system architecture"os.name" Operating system name"os.version" Operating system version"path.separator" Path separator (for example, ":")"user.dir" User's current working directory"user.home" User home directory"user.name" User account name
交通大學資訊工程學系 蔡文能 io-第 42頁
Java Java Input/Output
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.
交通大學資訊工程學系 蔡文能 io-第 43頁
Java Java Input/Output
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
交通大學資訊工程學系 蔡文能 io-第 44頁
Java Java Input/Output
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); }}
交通大學資訊工程學系 蔡文能 io-第 45頁
Java Java Input/Output
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.
交通大學資訊工程學系 蔡文能 io-第 46頁
Java Java Input/Output
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 managerUsing 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.
交通大學資訊工程學系 蔡文能 io-第 47頁
Java Java Input/Output
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;}
交通大學資訊工程學系 蔡文能 io-第 48頁
Java Java Input/Output
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; }
交通大學資訊工程學系 蔡文能 io-第 49頁
Java Java Input/Output
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!");}
交通大學資訊工程學系 蔡文能 io-第 50頁
Java Java Input/Output
Implementing a Security ManagerImplementing 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.
交通大學資訊工程學系 蔡文能 io-第 51頁
Java Java Input/Output
Operations On Approved BycheckAccept(String host, int port)checkConnect(String host, int port)checkConnect(String host, int port, Object executionContext)
sockets
checkListen(int port)checkAccess(Thread thread)threadscheckAccess(ThreadGroup threadgroup)
class loader checkCreateClassLoader()checkDelete(String filename)checkLink(String library)checkRead(FileDescriptor filedescriptor)checkRead(String filename)checkRead(String filename, Object executionContext)checkWrite(FileDescriptor filedescriptor)
file system
checkWrite(String filename)
交通大學資訊工程學系 蔡文能 io-第 52頁
Java Java Input/Output
Operations On Approved Byinterpreter checkExit(int status)package checkPackageAccess(String
packageName)checkPackageDefinition(String packageName)
properties checkPropertiesAccess()checkPropertyAccess(String key)checkPropertyAccess(String key, String def)
networking checkSetFactory()windows checkTopLevelWindow(Object window)
Cont.
交通大學資訊工程學系 蔡文能 io-第 53頁
Java Java Input/Output
Miscellaneous System Methods
Copying Arrayspublic static void arraycopy(Object source, int srcIndex, Object dest, int destIndex, int length )
交通大學資訊工程學系 蔡文能 io-第 54頁
Java Java Input/Output
public class ArrayCopyTest { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); }}
Note that the destination array must be allocated before you call arraycopy and must be large enough to contain the data being copied.
交通大學資訊工程學系 蔡文能 io-第 55頁
Java Java Input/Output
Getting the Current Time The currentTimeMillis method returns the current time.
In milliseconds.
Since 00:00:00, January 1, 1970.
The time difference between mouse clicks is used to determine whether a user double clicked.
If the time period between the clicks is smaller than 200 milliseconds, the two mouse clicks are interpreted as a double mouse click.
currentTimeMillis
public static long currentTimeMillis()
交通大學資訊工程學系 蔡文能 io-第 56頁
Java Java Input/Output
Examplepublic class TimingIsEverything extends java.applet.Applet { public long firstClickTime = 0; public String displayStr; public void init() { displayStr = "Double Click Me"; addMouseListener(new MyAdapter()); } public void paint(Graphics g) { g.drawRect(0, 0, getSize().width-1,
getSize().height-1); g.drawString(displayStr, 40, 30); } class MyAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent evt) { long clickTime = System.currentTimeMillis(); long clickInterval = clickTime - firstClickTime; if (clickInterval < 300) {
displayStr = "Double Click!! (Interval = "+
clickInterval + ")";firstClickTime = 0;
} else { displayStr = "Single Click!!";firstClickTime = clickTime;
} repaint(); }
}}
注意還需要 import 一些 package 的 class
再注意 : java.awt.* 並不包括java.awt.event.*
交通大學資訊工程學系 蔡文能 io-第 57頁
Java Java Input/Output
exit
Exiting the Runtime Environment To exit the Java interpreter, call the System.exit method:
System.exit(-1); The interpreter exits with the integer exit code that you specify to
the exit method. The exit method causes the Java interpreter to exit, not just
your Java program.
交通大學資訊工程學系 蔡文能 io-第 58頁
Java Java Input/Output
Input/Output Streaming
Input Stream
Output Stream
交通大學資訊工程學系 蔡文能 io-第 59頁
Java Java Input/Output
Model
Reading
open a stream
while more information
read information
close the stream
Writing
open a stream
while more information
write information
close the stream
交通大學資訊工程學系 蔡文能 io-第 60頁
Java Java Input/Output
Byte Streams vs. Character Streams
Divided into two class hierarchies based on the data type (either characters or bytes) on which they operate.
交通大學資訊工程學系 蔡文能 io-第 61頁
Java Java Input/Output
Data Sink Streams vs. Processing Streams
交通大學資訊工程學系 蔡文能 io-第 62頁
Java Java Input/Output
Character Streams
Subclasses of Reader and Writer implement specialized streams.
They are divided into two categories: Those that read from or write to data sinks.
(shown in gray in the following figures) Those that perform some sort of processing.
(shown in white in the following figures)
They both can handle any 16-bit characters in the Unicode character set.
交通大學資訊工程學系 蔡文能 io-第 63頁
Java Java Input/OutputCharacter Stream Family
交通大學資訊工程學系 蔡文能 io-第 64頁
Java Java Input/Output
Reader (Character Input Stream)
java.io Class Reader --- Since: JDK1.1
java.lang.Object | +-- java.io.Reader Direct Known Subclasses:
BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader
交通大學資訊工程學系 蔡文能 io-第 65頁
Java Java Input/Output
Writer (Character Output Stream)
java.io Class Writer --- Since: JDK1.1
java.lang.Object | +-- java.io.Writer
Direct Known Subclasses: BufferedWriter, CharArrayWriter, FilterWriter,
OutputStreamWriter, PipedWriter, PrintWriter, StringWriter
交通大學資訊工程學系 蔡文能 io-第 66頁
Java Java Input/Output
Byte Streams
Programs should use the byte streams, descendants of InputStream and OutputStream, to read and write 8-bit bytes.
These streams are used to read and write binary data such as images and sounds.
Subclasses of InputStream and OutputStream provide specialized I/O. Dividing into two categories: data sink streams and processing
streams.
交通大學資訊工程學系 蔡文能 io-第 67頁
Java Java Input/OutputByte Stream family
Java.lang.System.in
System.out
System.err
交通大學資訊工程學系 蔡文能 io-第 68頁
Java Java Input/Output
InputStream (Byte Input Stream)
java.io Class InputStream --- Since: JDK1.0
java.lang.Object | +-- java.io.InputStream
Direct Known Subclasses: AudioInputStream, ByteArrayInputStream, FileInputStream,
FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream
交通大學資訊工程學系 蔡文能 io-第 69頁
Java Java Input/Output
OutputStream (Byte Output Stream)
java.io Class OutputStream --- Since: JDK1.0
java.lang.Object | +-- java.io.OutputStream
Direct Known Subclasses: ByteArrayOutputStream, FileOutputStream, FilterOutputStream,
ObjectOutputStream, OutputStream, PipedOutputStream
交通大學資訊工程學系 蔡文能 io-第 70頁
Java Java Input/Output
C 裡面的 stderr, stdin, stdout
C++ 的 cerr, cin, cout
交通大學資訊工程學系 蔡文能 io-第 71頁
Java Java Input/Output
Similar APIs
Reader and InputStream define similar APIs but for different data types. int read()int read(char cbuf[])int read(char cbuf[], int offset, int length)
int write()int write(byte cbuf[])int write(byte cbuf[], int offset, int length)
Byte input Stream
Character input Stream
交通大學資訊工程學系 蔡文能 io-第 72頁
Java Java Input/Output
Data Sink Streams -- Outline
Sink Type Character Streams Byte StreamsMemory CharArrayReader,
CharArrayWriterByteArrayInputStream,ByteArrayOutputStream
StringReader,StringWriter
StringBufferInputStream
Pipe PipedReader,PipedWriter
PipedInputStream,PipedOutputStream
File FileReader,FileWriter
FileInputStream,FileOutputStream
交通大學資訊工程學系 蔡文能 io-第 73頁
Java Java Input/Output
Data Sink Streams (I)
CharArrayReader/CharArrayWriterByteArrayInputStream/ByteArrayOutputStream Use these streams to read from and write to memory. You create these streams on an existing array. Then use the read and write methods to read from or write to the
array.StringReader/StringWriter and StringBufferInputStream Use StringReader to read characters from a String as it
lives in memory. StringWriter collects the characters written to it in a StringBuffer, which can then be converted to a String.
StringBufferInputStream reads bytes from a StringBuffer.
交通大學資訊工程學系 蔡文能 io-第 74頁
Java Java Input/Output
Data Sink Streams (II)
FileReader/FileWriter and FileInputStream/FileOutputStream These streams are used to read from or write to a file on the native
file system. FileInputStream is meant for reading streams of raw bytes such
as image data. For reading streams of characters, consider using FileReader.
FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.
PipedReader/PipedWriter and PipedInputStream/PipedOutputStream Implement the input and output components of a pipe. Pipes are used to channel the output from one program (or thread)
into the input of another.
交通大學資訊工程學系 蔡文能 io-第 75頁
Java Java Input/Output
File Streams
The file streams -- FileReader, FileWriter, FileInputStream, and FileOutputStream
-- each read or write from a file on the native file system.
FileReader and FileWriter read and write 16-bit characters. Most native file systems are based on 8-bit bytes. These streams encode the characters as they operate according
to the default character-encoding scheme.
交通大學資訊工程學系 蔡文能 io-第 76頁
Java Java Input/Output
File
java.io Class File --- Since: JDK1.0
java.lang.Object | +-- java.io.File
All Implemented Interfaces: Comparable, Serializable
public class File extends Object implements Serializable, Comparable { /* … */ }
交通大學資訊工程學系 蔡文能 io-第 77頁
Java Java Input/Output
File Streams -- Example
import java.io.*;public class Copy { public static void main(String[] args)
throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c;
while ( (c = in.read()) != -1 ) out.write(c);
in.close(); out.close(); }}
-1 means EOF
(End Of File)
交通大學資訊工程學系 蔡文能 io-第 78頁
Java Java Input/Output
File Streams – Example (cont.)
import java.io.*;
public class TestReadFile {
public static void main(String arg[]) throws Exception {
FileReader fr =new FileReader("c:\\homework\\test.txt");
BufferedReader br = new BufferedReader( fr ); do { // read data line by line
String data = br.readLine();
if(data==null) break; // End Of File System.out.println(data);
} while(true);
} //main
}
交通大學資訊工程學系 蔡文能 io-第 79頁
Java Java Input/Output
Example of Processing StreamsWhen to use pipe streams Pipes are used to channel the output from one program (or thread)
into the input of another program. Without pipe streams, the program would have to store the results
somewhere (such as in a file or in memory) between each step.
交通大學資訊工程學系 蔡文能 io-第 80頁
Java Java Input/Output
Pipe StreamsWith pipe streams, the output from one method could be piped into the next.
交通大學資訊工程學系 蔡文能 io-第 81頁
Java Java Input/Output
Example using Pipe StreamsThe calling sequence of the reverse and sort methods from the main method.FileReader words = new FileReader("words.txt");Reader rhymingWords = reverse(sort(reverse(words)));
The reverse method :public static Reader reverse(Reader source) { BufferedReader in = new BufferedReader(source);
PipedWriter pipeOut = new PipedWriter(); PipedReader pipeIn = new PipedReader(pipeOut); PrintWriter out = new PrintWriter(pipeOut);
new ReverseThread(out, in).start();
return pipeIn;}
交通大學資訊工程學系 蔡文能 io-第 82頁
Java Java Input/Output
Example: Annotation The bold statements in reverse create both ends of a pipe -- a PipedWriter and a PipedReader -- and connects them by constructing the PipedReader "on" the PipedWriter.
Using Streams to Wrap Other StreamsBufferedReader in = new BufferedReader(source);...PrintWriter out = new PrintWriter(pipeOut);
First line opens a BufferedReader on source, the argument to reverse (a Reader). So, it can use BufferedReader's convenient readLine method.
The PipedWriter is wrapped in a PrintWriter so that the program can use PrintWriter's convenient println method.
交通大學資訊工程學系 蔡文能 io-第 83頁
Java Java Input/Output
Processing Streams -- Summary
Process CharacterStreams Byte StreamsBuffering BufferedReader,
BufferedWriterBufferedInputStream,BufferedOutputStream
Filtering FilterReader,FilterWriter
FilterInputStream,FilterOutputStream
Converting betweenBytes and Characters
InputStreamReader,OutputStreamWriter
Concatenation SequenceInputStreamObject Serialization ObjectInputStream,
ObjectOutputStreamData Conversion DataInputStream,
DataOutputStreamCounting LineNumberReader LineNumberInputStreamPeeking Ahead PushbackReader PushbackInputStreamPrinting PrintWriter PrintStream
交通大學資訊工程學系 蔡文能 io-第 84頁
Java Java Input/Output
Processing Streams (1/3)
BufferedReader and BufferedWriter
BufferedInputStream and BufferedOutputStream Buffer data while reading or writing
Reducing the number of accesses required on the original data source.
Buffered streams are typically more efficient than similar nonbuffered streams.
FilterReader and FilterWriter
FilterInputStream and FilterOutputStream Abstract classes, like their parents. They define the interface for filter streams, which filter data as it's
being read or written.
交通大學資訊工程學系 蔡文能 io-第 85頁
Java Java Input/Output
Processing Streams (2/3)
InputStreamReader and OutputStreamWriter InputStreamReader reads bytes from an InputStream and
converts them to characters using either the default character-encoding or a character-encoding specified by name.
OutputStreamWriter converts characters to bytes using either the default character-encoding or a character-encoding specified by name and then writes those bytes to an OutputStream.
SequenceInputStream Concatenates multiple input streams into one input stream. ObjectInputStream and ObjectOutputStream Used to serialize objects. DataInputStream and DataOutputStream Read or write primitive Java data types in a machine-independent format. Note the byte-ordering problem. (若是不同電腦系統換資料 )
交通大學資訊工程學系 蔡文能 io-第 86頁
Java Java Input/Output
Processing Streams (3/3)
LineNumberReader
LineNumberInputStream Keeps track of line numbers while reading.
PushbackReader and PushbackInputStream Two input streams each with a 1-character (or byte) pushback
buffer. When reading data from a stream, you will find it useful to peek at
the next item in the stream in order to decide what to do next.
PrintWriter and PrintStream Contain convenient printing methods. These are the easiest streams to write to, so you will often see
other writable streams wrapped in one of these.
交通大學資訊工程學系 蔡文能 io-第 87頁
Java Java Input/Output
Example: Concatenate Files (1/3)
How to Concatenate Filesimport java.io.*;
public class Concatenate { public static void main(String[] args) throws IOException { ListOfFiles mylist = new ListOfFiles(args);
SequenceInputStream s = new SequenceInputStream(mylist);
int c;
while ((c = s.read()) != -1) System.out.write(c);
s.close(); }}
交通大學資訊工程學系 蔡文能 io-第 88頁
Java Java Input/Output
Example: Concatenate Files (2/3)import java.util.*;import java.io.*;
public class ListOfFiles implements Enumeration { private String[] listOfFiles; private int current = 0; public ListOfFiles(String[] listOfFiles) {
this.listOfFiles = listOfFiles; } public boolean hasMoreElements() {
if (current < listOfFiles.length) return true; else return false; }
交通大學資訊工程學系 蔡文能 io-第 89頁
Java Java Input/Output
Example: Concatenate Files (3/3)
public Object nextElement() { InputStream in = null;
if (!hasMoreElements()) throw new NoSuchElementException("No more files.");else { String nextElement = listOfFiles[current]; current++; try {
in = new FileInputStream(nextElement); } catch (FileNotFoundException e) {
System.err.println("ListOfFiles: Can't open " +
nextElement); } } return in;
}
交通大學資訊工程學系 蔡文能 io-第 90頁
Java Java Input/Output
Example: Filtered Streams (1/3)
Working with Filtered Streams Using Filtered Streams
To use a filtered input or output stream, attach the filtered stream to another input or output stream.
DataInputStream dis = new DataInputStream(System.in);
String input;while ((input = dis.readLine()) != null) { . . . // readLine( ) deprecated}
交通大學資訊工程學系 蔡文能 io-第 91頁
Java Java Input/Output
Example: Filtered Streams (2/3) Using DataInputStream and DataOutputStream
DataOutputStream must be attached to some other OutputStream.
DataOutputStream dos = new DataOutputStream( new FileOutputStream("invoice1.txt"));
Use DataOutputStream's specialized writeXXX methods to write the invoice data according to the type of data being written.
for (int i = 0; i < prices.length; i++) { dos.writeDouble(prices[i]); dos.writeChar('\t'); dos.writeInt(units[i]); dos.writeChar('\t'); dos.writeChars(descs[i]); dos.writeChar('\n');}dos.close();
Write as:19.99 12 Java T-shirt9.99 8 Java Mug
交通大學資訊工程學系 蔡文能 io-第 92頁
Java Java Input/Output
Example: Filtered Streams (3/3)
reads the data back in using DataInputStream's specialized readXXX methods.
try { while (true) { price = dis.readDouble(); dis.readChar(); // throws out the tab unit = dis.readInt(); dis.readChar(); // throws out the tab desc = dis.readLine(); System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; } } catch (EOFException e) {}System.out.println("For a TOTAL of: $" + total);dis.close();
交通大學資訊工程學系 蔡文能 io-第 93頁
Java Java Input/Output
Write Your Own Filtered Streams
Writing Your Own Filtered StreamsA list of steps to take when writing your own filtered input and output streams:
Create a subclass of FilterInputStream and FilterOutputStream.
Override the read and write methods. Override any other methods that you might
need. Make sure the input and output streams work
together.
交通大學資訊工程學系 蔡文能 io-第 94頁
Java Java Input/Output
Random Access Files (RAFs)Example: Zip archives contain files and are typically compressed to save
space. Zip archives also contain a dir-entry at the end
Indicating where the various files contained within the zip archive begin.
Without RAFs, you have to do the following:Open the zip archive. Search through the zip archive until you located the file you wanted to extract.Extract the file.Close the zip archive.
交通大學資訊工程學系 蔡文能 io-第 95頁
Java Java Input/Output
With RAFs
You can extract the same file from the zip archive more efficiently using the seek feature of a random access file: Open the zip archive. Seek to the dir-entry and locate the entry for the file
you want to extract from the zip archive. Seek (backwards) within the zip archive to the position
of the file to extract. Extract the file. Close the zip archive.
交通大學資訊工程學系 蔡文能 io-第 96頁
Java Java Input/Output
RAFs
Using Random Access Files The RandomAccessFile class implements both the DataInput and
DataOutput interfaces for reading and writing. When create a RandomAccessFile, you must indicate whether you will be
just reading the file or also writing to it.
new RandomAccessFile("farrago.txt", "r");
new RandomAccessFile("farrago.txt", "rw");
When the file is first created, the file pointer is 0, indicating the beginning of the file.
Calls to the readXXX and writeXXX methods adjust the file pointer by the number of bytes read or written.
交通大學資訊工程學系 蔡文能 io-第 97頁
Java Java Input/Output
Manipulating Pointers
RandomAccessFile contains three methods for explicitly manipulating the file pointer. skipBytes
Moves the file pointer forward the specified number of bytes.
seek
Positions the file pointer just before the specified byte.
getFilePointer
Returns the current byte location of the file pointer.
交通大學資訊工程學系 蔡文能 io-第 98頁
Java Java Input/Output
Writing Filters for RAFsCheckedDataOutput vs. CheckedOutputStream CheckedDataOutput does not extend FilterOutputStream. Instead, it implements the DataOutput interface.
public class CheckedDataOutput implements DataOutput
CheckedDataOutput declares a private variable to hold a DataOutput object.private DataOutput out;
The constructor for CheckedDataOutput is created on a DataOutput object rather than on an OutputStream. public CheckedDataOutput(DataOutput out, Checksum cksum) { this.cksum = cksum; this.out = out;}
This constructor does not call super(out) like the CheckedOutputStream constructor did.
This is because CheckedDataOutput extends from Object rather than a stream class.
交通大學資訊工程學系 蔡文能 io-第 99頁
Java Java Input/Output
CheckedDataInput vs. CheckedInputStream
CheckedDataInput vs. CheckedInputStreamCheckedDataInput requires the same changes as CheckedDataOuput:
It does not derive from FilterInputStream but implements the DataInput interface instead.
It declares a private variable to hold a DataInput object which it wraps.
The constructor for CheckedDataInput requires a DataInput object rather than an InputStream.
交通大學資訊工程學系 蔡文能 io-第 100頁
Java Java Input/Output
Example (1/2)
The Main Programs This example has two main programs to test the new filters :
CheckedDITest : which runs the filters on sequential access files (DataInputStream and DataOutputStream objects)CheckedRAFTest : which runs the filters on random access files (RandomAccessFiles objects).
CheckedDITest creates a DataInputStream and a DataOutputStream and uses the checksum filter on those.
cis = new CheckedDataInput( new DataInputStream(new FileInputStream("farrago.txt")), inChecker);cos = new CheckedDataOutput( new DataOutputStream(new FileOutputStream("outagain.txt")), outChecker);
交通大學資訊工程學系 蔡文能 io-第 101頁
Java Java Input/Output
Example (2/2)
CheckedRAFTest creates two RandomAccessFiles, one for reading and one for writing, and uses the checksum filter on those:
cis = new CheckedDataInput( new RandomAccessFile("farrago.txt", "r"),inChecker);
cos = new CheckedDataOutput(new RandomAccessFile("outagain.txt", "rw"), outChecker);
When you run either of these programs you should see the following output:
Input stream check sum: 736868089Output stream check sum: 736868089
交通大學資訊工程學系 蔡文能 io-第 102頁
Java Java Input/Output
And the Rest . . . java.io contains the following classes and interfaces: File
Represents a file on the native file system.You can create a File object for a file on the native file system and then query the object for information about that file (such as its full pathname).
FileDescriptor Represents a file handle (or descriptor) to an open file or an open socket.
StreamTokenizer Breaks the contents of a stream into tokens.Tokens are the smallest unit recognized by a text-parsing algorithm (such as words, symbols). A StreamTokenizer object can be used to parse any text file.
Parsing a Java source file into variable names, operators….. Parsing an HTML file into HTML tags.
FilenameFilterUsed by the list method in the File class to determine which files in a directory to list. The FilenameFilter accepts or rejects files based on their names.
交通大學資訊工程學系 蔡文能 io-第 103頁
Java Java Input/Output
Other Input/Output Streams
Other input and output streams in the java.util.zip package, including these: CheckedInputStream and CheckedOutputStream
An input and output stream pair that maintains a checksum as the data is being read or written.
DeflaterOutputStream and InflaterInputStreamCompresses or uncompresses the data as it is being read or written.
GZIPInputStream and GZIPOutputStream Reads and writes compressed data in the GZIP format.
ZipInputStream and ZipOutputStream Reads and writes compressed data in the ZIP format.
交通大學資訊工程學系 蔡文能 io-第 104頁
Java Java Input/Output
Introduction to Java Programming
謝謝捧場http://www.csie.nctu.edu.tw/~tsaiwn/java/
蔡文能