天天看點

java 标準I/O流

1.輸入流的重新包裝執行個體

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

PrintWriter out = new PrintWriter(System.out,true);

String s;

while((s = br.readLine()) != null && s.length() != 0){

out.println(s.toUpperCase());

}

2.标準I/O重定向

對于标準輸入流是從鍵盤輸入,輸出流時向控制台輸出,我們可以通過下面方法對流重定向

static void setIn(PrintStream in):對标準輸入重定向

static void setOut(PrintStream out):對标準輸出流重定向

static void setErr(PrintStream err):對标準錯誤輸出流重定向

執行個體:

PrintStream console = System.out;

BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));

PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(filename)));

//對标準輸入重定向

System.setIn(in);

//對标準輸出重定向

System.setOut(out);

//對标準錯誤輸出重定向

System.setErr(out);

//建立重定向輸入後的輸入流

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String s;

//重輸入檔案中一行行讀取資料

while((s = br.readLine())!=null){

System.out.println(s);

}

out.close();

//将輸出定向回控制台輸出

System.setOut(console);

3.随機通路檔案類

ReadomAccessFile類沒有繼承InputStream和OutputStream,而是直接繼承Object,并且實作DataInput和DataOutput接口

生成一個随機通路檔案類要指明檔案名和讀/寫(r/w)模式

比如:RandomAccessFile raf = new RandomAccessFile(filename,"rw");//可讀可寫

随機讀取檔案類的主要操作有

long getFilePointer():擷取目前檔案指針位置

void seek(long pos):移動檔案指針到指定的位置,從0開始計算位置

int skipBytes(int n):将檔案指針向檔案末尾移動指定的n個位元組,傳回實際移動的位元組數,若n<0則不發生移動