java中流的分類
1.按數據流的方法不同可以分為輸入流和輸出流
2.按處理數據單位的不同可以分為字節流和字符流
3.按功能的不同可以分為節點流和處理流
JDK所提供的所有流類型位于java.io內分別繼承自一下四種抽象流類型
字節流 | 字符流 | |
---|---|---|
輸入流 | InputStream | Reader |
輸出流 | OutputStream | Writer |
字節流
一個字節一個字節的讀寫
1.FileInputStream
FileInputStream in = null;
int b =0;
try {
in = new FileInputStream("f:\\test.txt");
} catch (FileNotFoundException e) {
System.out.print("文件找不到");
e.printStackTrace();
}
try {
while ((b =in.read()) != -1){
System.out.print((char)b);//這么轉漢字(因為漢子是2個字節)會出錯
}
in.close();
} catch (IOException e) {
System.out.println("文件讀取錯誤");
e.printStackTrace();
}
2.FileOutputStream
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream("f:\\test.txt");
out = new FileOutputStream("f:\\copyTest.txt");
} catch (FileNotFoundException e) {
System.out.print("文件找不到");
e.printStackTrace();
}
try {
while ((b =in.read()) != -1){
out.write(b);
}
in.close();
out.close();
} catch (IOException e) {
System.out.println("文件復制完成");
e.printStackTrace();
}
字符流
一個字符一個字符的讀寫
1.FileReader
Reader read = null;
int b =0;
try {
read = new FileReader("f:\\test.txt");
} catch (FileNotFoundException e) {
System.out.print("文件找不到");
}
try {
while ((b =read.read()) != -1){
System.out.print((char)b);
}
read.close();
} catch (IOException e) {
e.printStackTrace();
}
2.FileWriter
Reader read = null;
Writer writer = null;
int b = 0;
try {
read = new FileReader("f:\\test.txt");
writer = new FileWriter("f:\\writerCopy");
} catch (FileNotFoundException e) {
System.out.print("文件找不到");
}
try {
while ((b =read.read()) != -1){
writer.write(b);
}
read.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}