Console/File IO
import static靜態導入
一般我們導入一個類都用 import com.***.ClassName;而靜態導入是這樣:import static com.....ClassName.*;這裏多了個static和類名後麵的“.*” ,意思是導入這個類裏的靜態方法。當然,也可以隻導入某個靜態方法,隻要把 .* 換成靜態方法名就行了。
然後在這個類中,就可以直接用方法名調用靜態方法,而不必用ClassName.方法名 的方式。
這種方法的好處就是可以簡化一些操作,例如打印操作System.out.println(...);就可以將其寫入一個靜態方法print(...),在使用時直接print(...)就可以了。
toString()
public class ll { public String toString(){ return "hehe"; } public static void main(String[] args) { // TODO Auto-generated method stub ll obj=new ll(); System.out.print(obj);//hehe } } /*toString()是一個特殊的方法,把一個類轉換成String時就會自動調用*/
嵌套函數調用io
//: net/mindview/util/Print.java // Print methods that can be used without // qualifiers, using Java SE5 static imports: package net.mindview.util; import java.io.*; public class Print { // Print with a newline: public static void print(Object obj) { System.out.println(obj); } // Print a newline by itself: public static void print() { System.out.println(); } // Print with no line break: public static void printnb(Object obj) { System.out.print(obj); } // The new Java SE5 printf() (from C): public static PrintStream printf(String format, Object... args) { return System.out.printf(format, args); } } ///:~
其他文件中隻需import static net.mindview.util.Print.*;
就可以print()直接輸出了
File 讀取
方法一:File->FileReader->Scanner
方法二: File->FileInputStream->InputStreamReader->BufferedReader
方法三: File->FileReader->BufferedReader
Scanner
scanner對象把待讀入的數據都理解為字符串,若要把"123"轉化為int,那麼這個轉化過程不能免。
next()方法讀入下一個字符串,定界符就是空格、換行、製表符之類的,跟cpp默認的cin>>一致,當然也可以自定義。
幾個常用方法:
Pattern delimiter()
返回此 Scanner 當前正在用於匹配分隔符的 Pattern。
boolean hasNext()
判斷掃描器中當前掃描位置後是否還存在下一段。
boolean hasNextLine()
如果在此掃描器的輸入中存在另一行,則返回 true。
String next()
查找並返回來自此掃描器的下一個完整標記。
String nextLine()
此掃描器執行當前行,並返回跳過的輸入信息。
useDelimiter()
Sets this scanner's delimiting pattern to a pattern constructed from the specified String.
next()方法讀入下一個字符串,定界符就是空格、換行、製表符之類的,跟cpp默認的cin>>一致,當然也可以自定義。
幾個常用方法:
Pattern delimiter()
返回此 Scanner 當前正在用於匹配分隔符的 Pattern。
boolean hasNext()
判斷掃描器中當前掃描位置後是否還存在下一段。
boolean hasNextLine()
如果在此掃描器的輸入中存在另一行,則返回 true。
String next()
查找並返回來自此掃描器的下一個完整標記。
String nextLine()
此掃描器執行當前行,並返回跳過的輸入信息。
useDelimiter()
Sets this scanner's delimiting pattern to a pattern constructed from the specified String.
File 新建及寫入
Windows中空格為\r\n 注意\r在\n前麵。
Path
jdk 1.7及以後才出現的東東。
java.nio.file.Path
接口,代表文件路徑。
java.nio.file.Paths
這個類中有下麵這個靜態方法,根據指定的string得到Path對象。
Path java.nio.file.Paths.get(String first, String... more)
根據指定的string得到Path對象。
最後更新:2017-04-03 05:40:04