首页 > 代码库 > 输入输出流的四种方式

输入输出流的四种方式

1、FileInputStream和FileOutputStream

1 FileOutputStream fos = new FileOutputStream("D:\\输入输出流.txt");
2 String word = "输入输出流";
3 byte [] bytes = word.getBytes();
4 fos.write(bytes);
5 System.out.println("写入成功");
6 fos.close();

 

 1 FileInputStream fis = new FileInputStream("D:\\输入输出流.txt");
 2 byte [] bytes = new byte[1024];
 3 int data;
 4 while((data=http://www.mamicode.com/fis.read(bytes))!=-1){
 5       String str = new String(bytes,0,data);
 6       System.out.print(str);  
 7 }
 8 fis.close();
 9 /*
10      int data = http://www.mamicode.com/fis.read(bytes);>11      while(data!=-1){
12            String str = new String(bytes,0,data);
13            System.out.println(str);
14            data = http://www.mamicode.com/fis.read(bytes);    >15      }
16 */
  

 

2、FileReader和FileWriter

1 FileReader fr = new FileReader("E:\\输入输出流.txt");
2 char [] chars = new char[1024];
3 int data;
4 while((data=http://www.mamicode.com/fr.read(chars))!=-1){
5        String str = new String(chars,0,data);
6        System.out.println(str);
7 }
8 fr.close();
1 FileWriter fw = new FileWriter("E:\\输入输出流.txt");
2 String  word = "输入输出流";
3 fw.write(word);
4 System.out.println("写入成功");
5 fw.close();

3、BufferedReader和BufferedWriter

Reader fr = new FileReader("D:\\输入输出流.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while((line=br.readLine())!=null){
       System.out.println(line);
}
br.close();
fr.close();
Writer writer = new FileWriter("D:\\输入输出流.txt");
BufferedWriter bw = new BufferedWriter(writer);
String word = "输入输出流";
bw.write(word);
System.out.println("写入成功");
bw.close();
writer.close();

4、DataInputStream和DataOutputStream

InputStream is = new FileInputStream("D:\\输入输出流");
DataInputStream os = new DataInputStream(is);
OutputStream os = new FileOutputStream("E:\\输入输出流");
DataOutputStream dos = new DataOutputStream(os);
int data;
byte [] bytes = new byte[1024];
while((data = http://www.mamicode.com/dis.read(bytes))!=-1) {
       dos.write(bytes,0,data);
}

 

输入输出流的四种方式