Java输入输出流总结:
输入输出流可以按不同角度进行分类:
1.按数据流方向分为输入流输出流
2.按处理数据单位可以分为字符流和字节流(stream、reader)
3.按功能不同分为节点流和处理流
一.先看几个例子:(字符流与字节流)
(1)
package test.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class IOtest1 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int b=0;
FileInputStream in=null;
try {
in=new FileInputStream("D:\\java\\eclipseworkspace\\Test\\src\\test\\io\\IOtest1.java");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.print("找不到文件");
e.printStackTrace();
System.exit(-1);
}
try{
long num=0;
while((b=in.read())!=-1){
System.out.print((char)b);
num++;
}
in.close();
System.out.print("共读了"+num+"个字节");
}
catch(IOException e){
System.out.print("读取失败");
e.printStackTrace();
System.exit(-1);
}
}
}
注意:FileInputStream是对文件进行一个字节一个字节的读,由于汉字是作为一个字符是两个字节,所以读出来一个字节显示乱码。如果要是换成FileReader 类,则是一个字符一个字符的读,显示出来是完整的汉字。
(2)
package test.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IOtest2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileWriter fw=null;
FileReader fd=null;
try {
fd=new FileReader("D:\\java\\eclipseworkspace\\Test\\src\\test\\io\\IOtest1.java");
}
catch(FileNotFoundException e){
e.printStackTrace();
System.out.print("文件没有找到");
System.exit(-1);
}
try{
fw=new FileWriter("D:\\a.java");
int c=0;
while((c=fd.read())!=-1){
fw.write((char)c);
}
fw.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print("文件写入错误");
System.exit(-1);
}
}
}
二.先看几个例子:(缓冲流)
package test.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IOtest3 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String s=null;
BufferedReader br=new BufferedReader(new FileReader("D:\\a.java"));
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\a.java"));
for(int a=0;a<=10;a++)
{
s=String.valueOf(Math.random());
bw.write(s);
}
bw.flush();
while((s=br.readLine())!=null){
System.out.println(s);
}
bw.close();
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}