输入输出流的四种方式

Posted AlexanderTheGreat

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了输入输出流的四种方式相关的知识,希望对你有一定的参考价值。

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=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 = fis.read(bytes);
11      while(data!=-1){
12            String str = new String(bytes,0,data);
13            System.out.println(str);
14            data = 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=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 = dis.read(bytes))!=-1) {
       dos.write(bytes,0,data);
}

 

以上是关于输入输出流的四种方式的主要内容,如果未能解决你的问题,请参考以下文章

学习笔记——原生js中常用的四种循环方式

mysql查看版本的四种方法

makefile变量的四种赋值方式

集合的四种输出方法

如何指定VLC的RTSP拉流方式(RTP over UDP/TCP)

Java 多线程:创建线程的四种方式