自学JAVA-11:IO流

1、流按照方向分:输入流和输出流。(以内存做为参照物)
当从数据源中,将数据读取到内存中时,叫做输入流也叫读取流。
当将内存中的数据写入到数据源时,叫做输出流也叫写入流。

2、流按照传输的内容分,:字节流、字符流和对象流。
无论是哪一种流底层部分都是以字节方式传输。所以,其本质都是字节流。但是为了方便程序员更好的操作字符数据和对象数据。所以,在字节流基础上做了一层包装形成了字符流和对象流。

字节流:抽象父类是InputStream和OutputStream
字符流:抽象父类是Reader和Writer

3、流操作的步骤:
①建立流
②操作流
③关闭流

操作文件时,如果文件不存在,那么读取流会抛出未找到文件异常,而写入流会创建新文件。

流操作的主要目的:数据的转换。

4、序列化:
当需要对对象进行传输时,由于对象中数据很庞大,无法直接传输。那么在传输之前,需要将对象打散成二进制的序列,以便传输,这个过程称为序列化过程;到达目的地后,又要将二进制序列还原成对象,这个过程称为反序列化过程。

所有需要实现对象序列化的对象必须首先实现Serializable接口。

java.io.NotSerializableException:当需要传输对象时,而该对象所在的类,没有实现序列化接口时抛出。

transient 关键字:属性的修饰符。表示在传输对象时,被transizent修饰的属性值不做传输。

字节流:

/** 读取流 */
public void readData() {
InputStream in = null;
  try {
  // 建立文件读取字节流
  in = new FileInputStream("//读取文件地址");
  int data = 0;

  // read()一次读取一个字节,返回读取的数据,当返回值为-1时,表示文件读取完毕
   while ((data = in.read()) != -1) {
     System.out.println(data);
    }
  byte[] by = new byte[1024];
  int len = 0;
  // 将流中的数据读取到字节数组中,返回当前读取的字节数。读取完毕,返回-1
  while ((len = in.read(by)) != -1) {
  System.out.println(len);
  }

} catch (Exception e) {
e.printStackTrace();
} finally {
  try {
  // 关闭流
  in.close();
} catch (IOException e) {
  e.printStackTrace();
    }
}

/** 写入流 */
public void writeData(String str) {
  OutputStream out = null;
try {
  // true表示追加方式写入数据
  out = new FileOutputStream("//写入地址", true);

  // 将字符串转换成字节数组
  out.write(str.getBytes());
} catch (Exception e) {
  e.printStackTrace();
} finally {
try {
  out.close();
} catch (IOException e) {
  e.printStackTrace();
  }
}


/**复制文件*/
public void copyFile() {
  InputStream in = null;
  OutputStream out = null;
  try {
  in = new FileInputStream("//读取地址");
  out = new FileOutputStream("//写入地址");
  byte[] by = new byte[1024];
  int len = 0;
  while ((len = in.read(by)) != -1) {
  //读取几个字节,就写入几个字节
  out.write(by,0,len);
}
} catch (Exception e) {
  e.printStackTrace();
} finally {
try {
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

字符流:
/**读取*/
public void readData() {
Reader r = null;
BufferedReader br = null;

try {
//建立文件读取流
r = new FileReader("//读取地址");
//套接流,在一个流的基础上,再套接一个流,也称为高级流
br = new BufferedReader(r);
String str = null;
//读取一行数据,以\n或回车作为结束符
while ((str = br.readLine()) != null) {

System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**写入*/
public void writerData(String str){
Writer w =null;
try {
w=new FileWriter("//写入地址", true);
w.write(str);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

猜你喜欢

转载自www.cnblogs.com/LYL6868/p/8976075.html