Java I/O流使用记录

2019-02-12  本文已影响1人  奋斗滴猩猩

参考书:《Java程序设计标准教程》

一、简介

java输入输出功能来自java.io.的抽象类:InputStream和OutputStream类、Reader和Writer类以及她们的子类,以流的形式处理数据。流是一组数据序列,JAVA中每个数据流都是一个对象,提供各种支持读入和写出操作流类

二、I/0的基本模式

输入流.png
输出流.png

三、以byte为数据单位的流类(InputStream、OutputStream)

3.1、InputStream类
基本方法:

InputStream is = System.inl // 获取控制台的输入流
// InputStream is = null ;
Try {
// is =  new InputStream();
Byte[] bs = new byte[1024];
Int i = is.read(bs); // 从输入流中读取数据到字节数组
Is.close(); // 关闭输入流
} catch (IOException e){
E.printStackTrace()
}

3.2、OutputStream类

实例:以控制台输出流
OutputStream out = null;
Try{
out = new OutputStream() ;
Byte[] bs = “实例是outputStream 输出流”。getBytes();// 将字符串变成字节数组
Out.write(bs); // 将字节数组的内容写到输出流
Out.close(); // 关闭输出流
}catch(Exception e){
E.printStackTrace()
}

四、以char为数据单位的流类(Reader、writer类)

4.1、Reader类

实例:
InputStreamReader isr = null;
Try {
Isr = new InputStream(????????????????????????????);// 获取输入流
Char[] cs = new char[]; //??????????
Isr.read(cs)
String s = new String(cs);
Isr.close();
}catch(Exception e) {
}

4.2、Writer类

五、常用I/0处理方式

5.1、文件类

5.3、文件的字节输入输出流
    程序运行期间,大部分数据是在内存中操作的,当程序关闭或结束,这些数据完全消失,但有些数据需要永久保存;使用文件输入输出流可以和指定的文件建立关联,然后把需要永久保存的数据输出到文件中,程序下次运行,可以从文件中取回这些数据;
    5.3.1创建文件字节输入流
    文件字节输入流可以从指定路径的文件中读取字节数据,文件字节输入流继承字InputStream类,并实现了读取输入流的各种方法,
创建文件字节输入流的常用构造方法:
1、FileInputStream(File file)-----new FileInputStream(file),使用File类型的文件对象创建FileInputStream类的实例对象(文件字节输入流)
2、FileInputStream(String s) ---s指文件的绝对路径、相对路径
3、创建文件字节输出流:关联指定路径的文件 ,数据通过文件字节输出流以字节为单位输出并保存到文件中。常用构造方法FileOutputStream(File file),FileOutputStram(String fileName)

// 写入文件
Private static String fileName = “xxxx”
Private static File file = new File(fileName);
// 将启动时间点存到文件 XXX中
Private static long date = System.currentTime();
// 文件开始写入
String dataStr;
Try{
If(!file.exist()) {
File.createNewFile(); // ?????????????????注意区分 mkdir(创建文件,只能用来创建文件夹,且只能创建一级目录,如果上级不存在,创建失败)\makdirs(只能用来创建文件夹,,能创建多级目录,如果上级不存在,自动创建,创建文件夹多用这个)\createNewFile(只能用来创建文件,且只能创建在存在的目录下创建文件,否则创建失败,)-----
}
dataStr = date + “”;
Byte[] data = dataStr.getBytes();
FileOutputStream os = new FileOutputStream(file);
Os.write(data); // 将数据流写入输出流
Os.flush(); // 刷新缓冲区
Os.close(); // 关闭输出流
}catch(Exception e) {
E.printStackTrace();
}
// 读取文件
Try{
If(!file.exist()){
File.createNewFile();
}
Byte[] data = new Byte[1024];
FileInputStream fis = new FileInputStream(file); //创建文件输入流
Int rs = 0;
String result;
While((rs = fis.read(data)) > 0) { //在循环中读取输入流的数据
Result += new String(data, 0, rs)
}
Fis.close();
}catch(Exception e){
E.printStackTrace();
}

4、文件的字符输入输出流
字节流一字节为单位传送数据,可以是任何类型的数据,文本,音频,视频,图片等,字符流以字符为单位传送数据,只能传送文本类型数据
FileReader(File file)
FileReader(String fileName)
FileWriter(File file)
FileWriter(String fileName)

Public void readFile(){
Try{
String filePath  = “xxxx”;
File file = new File(filePath);
FileReader reader = new FileReader(file);
Char[] data = new Char[512];
StringBuider sb = new StringBuilder();
Int rs = 0;
While((rs = reader.read(data)) > 0) {
sb .append(data, 0 , rs);
}
Reader.close();
}catch(Exception e) {
E.printStackTrace();
}
}
// 写入文件
Public void writeFile() {
Try{
String filePath = “xxxx”;
File file = new File(filePath);
FileWriter fw = new FileWriter(file);
Fw.write(.......)//将数据写入
}catch(Exception e) {
E.printStackTrace();
}
}

六、对象序列化

程序运行时需要保存一些数据,对于基本数据类型,直接保存到文件中,但对于复杂对象类型,需要将对象中不同的属性分解为基本数据类型,然后分别存到文件中,当程序再次运行时,需要建立新的对象,然后从文件中读取与对象相关的所有数据,再使用这些数据分别为对象的每个属性初始化
ObjectInput\ObjectOutput接口继承了DataInput和DataOutput接口,提供对基本数据类型和对象序列化的方法,使用对象序列化可以方便将对象写入输出流或者从输入流读取对象数据。
1、readObject()反序列化方法,从输入流中获取序列化的对象数据,用这些数据生成新的JAVA对象,在ObjectInput接口中,由ObjectInputStream类实现
Object object = readObject();注意类型的转换,根据所需
2、writeObject序列化方法
将对象写入输出流,输出流可以是文件输出流、网络输出流、其他输出流
writeObject(object) 注意:被序列化的对象必须实现serializable接口,否则无法实现序列化

Public class Worker implement Serializable{
Private String name;
Private String getName() {
Return name;}
Private void setName(String name) {
This.name = name;
}
}


Public static main(String[] args) {
Worker w = new Worker();
W.setName(“AAAA”);
// 序列化
Try {
FileOutputStream fo = new FileOutputStream(“./worker.dat”); // 在实例所在文件夹下创建文件worker.dat
ObjectOutputStream obj = new ObjectOutputStream(fo);
Obj.writeObject(worker)
}catch(Exception e) {
E.printStackTrace();
}
// 反序列化
Try{
FileInputStream fis = new FileInputStream(“./worker.dat”);
ObjectInputStream ois = new ObjectInputStream(fis);
Worker wor = (Worker)ois.readObject();
String name  = wor.getName();
}catch(Exception e) {
E.printStackTrace();
}
}

七、对文件及文件夹操作

7.1 复制文件
指将文件内容复制到指定位置的新文件中,如果目标文件不存在,以目标文件名创建新的文件,并将原有文件内容复制到该文件中,否则覆盖目标文件

String sourceFilePath = “./A.txt”;
String dFilePath = “./B.txt”;
File sourceFile= new File(sourceFilePath); // 创建原文件对象
File dFile = new File(dFilePath); // 创建目标文件对象
Try{
FileInputStream fis  = new FileInputStream(sourceFile); // 创建原文件字节输入流
FIleOutputStream fosD = new FileOutputStream(dFile); // 创建目标文件字节输出流
Byte[] data = new Byte[1024];
Int rs = -1;
While((rs = fis.read(data)) > 0) { // 在循环中读取输入流的数据
fosD.write(data, 0, rs); // 在循环中把数据写入输出流中
}
Fis.close();
fosD.close();
}catch(FileNotFoundException e) {
E.printStackTrace();
}

7.2 复制文件夹
文件夹中可能含有多个文件,或文件夹,必须对他们分别执行复制操作

Public void copy(File[] s, File d) {
If(!d.exists) {
d.mkdir();
}
For(int i = 0; i < s.length; i++) {
If(s[i].isFile()) { // 如果是文件类型,直接进行复制操作
Try{
FileInputStream fis = new FileInputStream(s[i]);
FileOutputStream fos = new FileOutputStream(new File(d.getPath()            + File.separator + s[i].getName()));
Int num = fis.avaliable();
Byte[] data = new byte[num];
If((fis.read(data)) !=  -1){
Out.write(data); // 复制文件内容
}
Fos.close();
Fis.close();

} catch(Exception e) {
      E.printStackTrace();
    }
 }

        If(s[i].isDirectory) { // 如果是文件夹类型
               File des =(new File(d.getPath()+ File.separator + s[i].getName());
              Des.mkdir();
             Copy(s[i].listFiles(), des); // 递归调用方法本身
         }
   }
}

7.3 删除文件夹
File类的delete方法用来删除指定文件,必须使用目标文件路径创建一个File类的实例对象

File file = new File(“./aaaa.txt”);
deleteFile(file);

Public void deleteFile(File file) {
    If(!file.exists()) {
       // 文件不存在,直接返回
      Return;
    }
   Boolean rs = file.delete();
}

7.4 分行写入文件
FileWriter类 封装到BufferWriter类的缓冲字符流中,实现缓冲字符输出流,并可以newLine()方法实现数据的分行写入

String filePath = “./file.txt”;
File file = new File(filePath);
Try{
    FileWriter fw = new FileWriter(file); // 创建文件字符输出流
    BufferedWriter bw = new BufferedWriter(fw); // 使用缓冲数据流封装输出流
    Bw.write(“分行写入文件”);
    Bw.newLine();  // 写入换行符
    Bw.write(“mmmm”);
    Bw.flush(); // 刷新缓冲区
} catch(IOException e) {
    E.printStackTrace();
}
上一篇 下一篇

猜你喜欢

热点阅读