2020.7.30第二十四天

1.今天学习字节流(1)输出字节流OutputStreamI/O中输出字节流的特点。

#OutputStream 是所有的输出字节流的父类,它是一个抽象类。

#ByteArrayOutputStream、FileOutputStream 是两种基本的介质流,它们分别向Byte数组和本地文件中写入数据。ObjectOutputStream 和所有FilterOutputStream 的子类都是装饰流。

使用字节输出流OutputStream定义如下。

public abstract class OutputStream extends Object implements Closeable,Flushable

在此类中定义了如下的几个常用方法。
0关闭流: public void close() throws IOException.
#写一组数据: public void write(byte[ ]b) throws IOExceptio.
#写一个数据: public void write(int b) throws lOException .但是要想将OutputStream
实例化,且进行文件操作,就要使用FileOutputStream子类。
#构造: public FileOutputStream(File file) throws FileNotFoundException.

字节流输出

 

 1 import java.io. FileOutputStream;
 2 import java.io. IOException;
 3 import java.io. OutputStream;
 4 public class FileoutStreamDemo{
 5 public static void main(String[] arga) throws IOException {
 6 out();
 7 }
 8 public static void out() throws IOException{
 9 OutputStream out = new FileOutputStream ("D:/Hello.txt");
10 String info = "Hello Java!!";
11 byte[] buf=info.getBytes ();
12 out.write (buf) ;
13 out.close ();
14 }
15 }

 

 

 追加内容

 1 import java.io. FileOutputStream;
 2 import java.io. IOException;
 3 import java.io. OutputStream;
 4 public class FileoutstreamDemo2 {
 5 public static void main (String[] args) throws IOException {
 6 out();
 7 }
 8 public static void out () {
 9 OutputStream out=null;
10 try {
11 out=new FileOutputStream ("D:/Hello.txt",true);
12 String info ="Hello PHP!!";
13 byte[] buf = info.getBytes();
14 out.write (buf);
15 }catch (IOException e){
16 e.printStackTrace();
17 }finally {
18 try {
19 if (out!=null)
20 out.close() ;
21 } catch (IOException e) {
22 e.printStackTrace ();
23 }
24 }
25 }
26 }

 

(2)输入字节流InputStream
I/O中输入字节流的特点:
#InputStream 是所有的输入字节流的父类,它是一个抽象类.
#BytcArrayInputStream. StringBufferInputStream. FileInputStream 是三种基本的介质
流,它们分别从Byte数组. StringBuffer和本地文件中读取数据. ObjectlnputStream
和所有FilterlnputStream的子类都是装饰流.
用户可以使用InputStream完成输入字节流的操作,此类定义如下。
public abstract class InputStream extends object implements Closeable
InputStream类中定义的方法如下。
#关闭: public void close() throws lOException.
#读取一个字节: public abstract int read() throws lOException.
#读取一组内 容: public int read(byte[ ] b) throws IOException.
读取文件,使用子类FileInputStream.

 1 import java.io. FileInputStream;
 2 import java.io. IOException;
 3 public class FileInputstreamDemo {
 4 public static void main (String[] args) throws IOException {
 5 in();
 6 }
 7 public static void in(){
 8 FileInputStream in = null; 
 9 try {
10 in=new FileInputStream("D:/Hello.txt");
11 byte[] buf = new byte[1024];
12 int len=-1;
13 while((len=in.read (buf))!=-1) {
14 String s=new String (buf,0,len);
15 System.out.println(s);
16 }
17 }catch (IOException e) {
18 e.printStackTrace();
19 }finally{
20 try {
21 if(in!=null)
22 in.close();
23 } catch (IOException e) {
24 e.printStackTrace();
25 }
26 }
27 }
28 }

 

 2.遇到的问题:不明白为什么在使用输入输出字节流时要用try

3.明天继续学习字符流

 

posted @ 2020-07-30 22:01  敲敲代代码码  阅读(106)  评论(0编辑  收藏  举报