你須要注意的java小細節(二)

這些都是一些小問題,可是有助於理解輸入輸出流。
InputStreamReader 中的一個 read()是每次只會從磁盤裏面讀取一個字節。它會很是頻繁的訪問磁盤。(想想,每次只從磁盤讀一個字節)
InputStreamReader 是字節流通向字符流的橋樑:它使用指定的 charset 讀取字節並將其解碼爲字符。它使用的字符集能夠由名稱指定或顯式給定,或者能夠接受平臺默認的字符集。
每次調用 InputStreamReader 中的一個 read() 方法都會致使從底層輸入流讀取一個或多個字節。要啓用從字節到字符的有效轉換,能夠提早從底層流讀取更多的字節,使其超過知足當前讀取操做所需的字節。
爲了達到最高效率,可要考慮在 BufferedReader 內包裝 InputStreamReader。例如:java

BufferedReader in
   = new BufferedReader(new InputStreamReader
import java.io.*;
import java.io.DataInputStream;
public  class   Main{
    public static void main(String[] args) throws  Exception {

      BufferedReader   reader= new BufferedReader(new InputStreamReader(new FileInputStream(new File("text.txt"))));

String line=null;
 while((line=reader.readLine())!=null){
     String[]  s=line.split("\\s+");

     for ( String single:s ) {
           System.out.println(single);
     }
    
 }
    }
}

(System.in));
\s匹配任意的空白符,包括空格,製表符(Tab),換行符,中文全角空格code

Java的重定向
JAVA支持標準的輸出輸入重定向。it

public  class   Main{
    public static void main(String[] args) throws  Exception {

       System.out.println("Hello World!");

    }
}

編譯之後,直接使用java Main >test.txt進行輸出重定向io

使用輸入重定向:編譯

public  class   Main{
    public static void main(String[] args) throws  Exception {
         Scanner sc=new Scanner(System.in);  
        while(sc.hasNextLine())  
        {  
            System.out.println(sc.nextLine());  
        }  
    }
}                                                                                                                                                                  
java  Main<text.txt;
相關文章
相關標籤/搜索