轉載請標明出處: http://blog.csdn.net/wu_wxc/article/details/51737361
本文出自【吳孝城的CSDN博客】
根據處理的數據類型可分爲:字節流、字符流
根據數據走向可分爲:輸入流、輸出流
字節流:可以處理所有類型的數據,在讀取時,讀到一個字節就返回一個字節。
在Java中以對應的類以”Stream”結尾
字符流:僅能處理純文本數據,如txt文本,它是在讀取到一個或多個字節後,查找指定的編碼表,然後將查找到的字符返回
在Java中對應的類以”Reader”或”Writer”結尾
輸入流和輸出流:
輸入流用於從源讀取數據,輸出流用於向目標寫數據
輸入流
package cn.wuxiaocheng;
import java.io.FileInputStream;
public class Inout {
public static void main(String[] args) {
try {
FileInputStream inputStream = new FileInputStream("test.txt");
// 在UTF-8中,一個漢字3個字節,一個"."1個字節,一個數字1個字節,一個換行2個字節
byte[] input = new byte[37];
inputStream.read(input);
String string = new String(input, "UTF-8");
System.out.println(string);
} catch (Exception e) {
}
}
}
**輸出流**
package cn.wuxiaocheng;
import java.io.FileOutputStream;
public class Output {
public static void main(String[] args) {
try {
FileOutputStream fileOut = new FileOutputStream("test.txt");
String str = "輸出的內容";
byte[] out = str.getBytes("UTF-8");
fileOut.write(out);
} catch (Exception e) {
}
}
}
下面是一個讀取鍵盤輸入的內容,從控制檯輸出的程序
package cn.wuxiaocheng;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class In {
public static void main(String[] args) throws IOException {
String c = null;
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("輸入文字回車輸出");
System.out.println("輸入end結束");
do {
// 字符串用readLine(),如果是char類型的字符可用read()
c = br.readLine();
System.out.println(c);
} while (!c.equals("end"));
}
}