java io流

*File类

File类是用来操作文件的类,但它不能操作文件中的数据,File实现了SerializableComparable<File>,支持序列化和排序。

(1):File类是文件和文件目录路径的抽象表示形式,与平台无关

(2):File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。

(3):File实例表示的文件或者文件目录可能存在也可能是不存在的

绝对路径:固定的路径,从磁盘盘符开始。例:c:/website/img/photo.jpg

相对路径:相对于某个位置开始。

例:c:/website/web/xz/index.htm ../表示上一级目录

c:/website/img/images/photo.jpg 在此例中index.htm中联接的photo.jpg应该怎样表示呢? 错误写法:../img/images/photo.jpg 这种写法是不正确的,在此例中对于index.htm文件来说../img/images/photo.jpg所代表的绝对路径是: c:/website/web/img/images/photo.jpg。 正确写法:可以使用../../img/images/photo.jpg的相对路径来定位文件

详情可见:

绝对路径和相对路径详解_相对路径和绝对路径-CSDN博客

构造方法:

File(String pathname) :通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。

File(String parent, String child) :从父路径名字符串和子路径名字符串创建新的 File实例。

File(File parent, String child) :从父抽象路径名和子路径名字符串创建新的 File实例。

import java.io.File;
import java.io.IOException;
​
public class File_Demo {
​
        public static void main(String[] args) throws IOException{
            //构造方法一:
            File file1 = new File("Hello.txt");//相对于当前moudle
            File file2 = new File("D:/feisi/fileTest.txt");
​
            System.out.println(file1);
            System.out.println(file1.getAbsoluteFile());
            System.out.println(file2);
​
            //构造方法二:
            File file3 = new File("D:/feisi","Hello.txt");
            System.out.println(file3);
​
            //构造方法三:
            File file4  = new File(file3,"World");
            System.out.println(file4);
​
        }
​
​
}

常用方法:

boolean createNewFile() :当且仅当具有该名称的文件尚不存在时,原子地创建一个由该抽象路径名命名的新的空文件。

boolean delete() :删除由此抽象路径名表示的文件或目录。

boolean exists() :测试此抽象路径名表示的文件或目录是否存在。

File getAbsoluteFile() :返回此抽象路径名的绝对形式。

String getAbsolutePath() :返回此抽象路径名的绝对路径名字符串。

long length() :返回由此抽象路径名表示的文件的长度。

boolean mkdir() :创建由此抽象路径名命名的目录。

boolean mkdirs() :创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录。

*io流

分类:

1.按数据流向分:输入流、输出流

2.按处理数据单位分:字节流,字符流

3.按功能分:节点流,处理流

io流四大基流
字节流:

InputStream(输入流)

OutputStream(输出流)

字符流:

Reader(输入流)

Writer (输出流)

注意:

1.这四个类都是抽象类

2.所有的流都有close()方法,用于关闭流,释放资源流会占用很多资源,用完后一定要关闭流,释放资源

3.所有的输出流都有flush()方法,用于刷新流,流是一个管道,这个方法表示将管道中剩余的数据强制全部输出,如果输出完之后不调用flush()方法可能会导致有部分数据残留在管道中,造成数据的丢失

4.以Stream结尾的都是字节流,以Reader或Writer结尾的都是字符流。

5.字节流什么类型的文件都可以读取,但是在读取文本类型的文件时,可能读取到中文字符的一半,因为字节流一次读取一个字节,而中文根据编码的不同,在UTF-8中一个汉字占三个字节,在Unicode编码中占两个字节,所以字节流可能读到中文字符的一半造成乱码,因此我们读取文本文件一般采用字符流,字符流也只能读取普通文本,图片,视频,声音等文件要用字节流。

文件流
文件字节流:
FileInputStream:

构造方法:

FileInputStream(String name): name为文件路径

FileInputStream fs = new FileInputStream("D:\\2100130221\\img\\banner.jpg");

FileInputStream(File file):

 File file = new File("D:\\2100130221\\img\\banner.jpg");
 FileInputStream fileinput = new FileInputStream(file);

常用方法:

int available() :返回文件有效的字节数

void close() :关闭此文件输入流并释放与流相关联的任何系统资源。

int read() :从该输入流读取一个字节的数据。

int read(byte[] b) :从该输入流读取最多 b.length个字节的数据为字节数组。

int read(byte[] b, int off, int len) :从该输入流读取最多 len字节的数据为字节数组。

long skip(long n) :跳过并从输入流中丢弃 n字节的数据。

package ClassDemo;
​
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
​
public class FileInputStreamDemo {
    public static void main(String[] args) {
        FileInputStream fis= null;
        try {
            fis = new FileInputStream("D:\\feisi\\calcCharNum.txt");
            System.out.println(fis.available());//文件有多少个字节
            byte[] bys = new byte[10];//一次读取10个字节
            int readcount = 0;
            while((readcount=fis.read(bys))!=-1){
                //也可以一次读完 byte[] bys = new byte[fis.available]; 不适合大文件
  //read()这个方法的返回值是读取到了多少个字节,如果没读到返回-1(文件末尾)
 //读取到多少个字节就转换多少个字节,不然会出现重复输出,因为读取过程是不断覆盖字符数组实现的,最后一次读取的字节数少于每次读取的字节数,就会导致没有全部覆盖,还留有上次读取的数据,导致重复输出
                System.out.print(new String(bys,0,readcount));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {//finally保证流一定关闭
            if(fis!=null){//避免空指针异常
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
​
    }
}



FileOutputStream:

FileOutputStream(String name):name为文件路径

FileOutputStream(String name, boolean append):name为文件路径,append为true表示在文件末尾追加;为false表示清空文件内容,重新写入,默认为false

FileOutputStream(File file):

FileOutputStream(File file, boolean append):append为true表示在文件末尾追加;为false表示清空文件内容,重新写入,默认为false

常用方法:

void write(int b):将指定的字节写入此输出流。

void write(byte[] b, int off, int len) :从指定的字节数组写入 len个字节,从偏移 off开始输出到此输出流

void write(byte[] b) :将 b.length字节从指定的字节数组写入此输出流。

void flush() :刷新此输出流并强制任何缓冲的输出字节被写出。

void close() :关闭此输出流并释放与此流相关联的任何系统资源。

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
​
public class FileOutputStreamDemo {
    public static void main(String[] args)  {
        FileOutputStream fos = null;
        try {
            //FileOutputStreamDemo.txt文件不存在的时候会自动创建
            //未指定append会将原文件清空造成数据丢失
            fos = new FileOutputStream("D:\\feisi\\FileOutputStreamDemo.txt",true);//指定append为true在文件末尾追加,防止数据丢失
            byte[] bys ={97,98,99};
            fos.write(bys);//写进文件的是abc
​
            //也可以将字符串转换为字节数组
            byte[] bys2 = "我爱中国".getBytes();
            fos.write(bys2);
            //写完刷新输出流
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fos!=null){
                //不为空关闭流,避免空指针异常
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
​
    }
}
​

文件字符流:(只能读取普通文本)
FileReader:

构造方法:

FileReader(String fileName):创建一个新的 FileReader ,给定要读取的文件的名称,即文件路径。

FileReader(File file) :创建一个新的 FileReader ,给出 File读取。

常用方法:

int read():读一个字符,返回值为该字符的ASCII码,读到末尾返回-1.

int read(char[] c): 读c数组长度的字节到c数组中,返回值为读到的字符个数;读到文件末尾返回-1

int read(char[] c, int off, int len): 从c数组off位置读len长度的字符到c数组中,返回值为读到的字符个数;读到文件末尾返回-1

long skip(long n): 跳过n个字符

void close(): 关闭文件输入流

boolean markSupported() :告诉这个流是否支持mark()操作。

void mark(int readAheadLimit) :标记流中的当前位置。

void reset() :重置流

package ClassDemo;
​
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
​
public class FileReaderDemo {
    public static void main(String[] args) {
        FileReader fr = null;
        try {
            fr = new FileReader("D:\\feisi\\FileOutputStreamDemo.txt");
            char[] ch = new char[4];
            int readcount = 0;
            while((readcount=fr.read(ch))!=-1){
                System.out.println(new String(ch,0,readcount));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fr!=null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

FileWriter:

构造方法:

FileWriter(String fileName):构造一个给定文件名的FileWriter对象。

FileWriter(String fileName, boolean append):构造一个FileWriter对象,给出一个带有布尔值的文件名,表示是否附加写入的数据。

FileWriter(File file):给一个File对象构造一个FileWriter对象

FileWriter(File file, boolean append):给一个File对象构造一个FileWriter对象。

常用方法:

void write(char[] cbuf) :写入一个字符数组。

void write(char[] cbuf, int off, int len) :将c数组off位置开始,len长度的字符写入文件中

void write(int c) :将一个字符写入文件

void write(String str) :将一个字符串写入文件

void write(String str, int off, int len) :从字符串off位置开始截取len长度的字符串写入文件

void flush() :刷新流。

void close() :关闭流,先刷新。

package ClassDemo;
​
import java.io.FileWriter;
import java.io.IOException;
​
public class FileWriterDemo {
    public static void main(String[] args) {
        FileWriter fw = null;
        try {
            fw = new FileWriter("D:\\feisi\\FileWriterDemo.txt",true);//append为true在末尾追加
            String str = "Hello,World!";
            fw.write(str);
            fw.write(str,0,4);//从0位置开始长度为4,即Hell
            //写完刷新
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
​

缓冲流与转换流:
BufferedReader:

构造方法:

BufferedReader(Reader in) :创建使用默认大小的输入缓冲区的缓冲字符输入流。

BufferedReader(Reader in, int sz) :创建使用指定大小的输入缓冲区的缓冲字符输入流。

常用方法:

int read() :读取一个字符,返回值为该字符ASCII码;读到文件末尾返回-1

int read(char[] c): 读c数组长度的字节到c数组中,返回值为读到的字符个数;读到文件末尾返回-1

String readLine(): 读取文件一行

long skip(long n): 跳过n个字符

void close(): 关闭文件输入流

package ClassDemo;
​
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
​
public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {
        FileReader fr = new FileReader("D:\\feisi\\FileWriterDemo.txt");
        // 当一个流的构造方法中需要一个流的时候,这个被传进来的流叫做:节点流。
        // 外部负责包装的这个流,叫做:包装流,还有一个名字叫做:处理流。
        //FileReader即是节点流,BufferedReader即是包装流
        BufferedReader br = new BufferedReader(fr);
        String str = null;
        while((str = br.readLine())!=null){
            System.out.println(str);
        }
​
        // 关闭流
        // 对于包装流来说,只需要关闭最外层流就行,里面的节点流会自动关闭。
        br.close();
    }
}
InputStreamReader(字节流->字符流):
package ClassDemo;
​
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
​
public class InputStreamReaderDemo {
    public static void main(String[] args) throws IOException {
        //BufferedReader构造方法只能传字符流
        //通过转换流InputStreamReader将字节流转换为字符流
        //FileInputStream fis = new FileInputStream("D:\\feisi\\FileWriterDemo.txt")
        //InputStreamReader isr = new InputStreamReader(fis)
        //BufferedReader br = new BufferedReader(isr)
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\feisi\\FileWriterDemo.txt")));
​
        String line = null;
        while((line = br.readLine()) != null){
            System.out.println(line);
        }
        
        // 关闭最外层
        br.close();
        
    }
}

BufferedWriter:
OutputStreamWriter:

BufferedWriter(Writer out) :创建使用默认大小的输出缓冲区的缓冲字符输出流。

BufferedWriter(Writer out, int sz) :创建一个新的缓冲字符输出流,使用给定大小的输出缓冲区。

常用方法:

void write(int c):将指定字符写入文件中

void write(char[] c, int off, int len): 将c素组off位置开始,len长度的字符写入文件中

void write(String str, int off, int len): 从字符串off位置开始截取len长度的字符串写入文件

void flush(): 刷新此输出流并强制写出所有缓冲的输出字符

void close(): 关闭文件输出流

package ClassDemo;
​
import java.io.*;
​
public class BufferedWriterDemo {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("D:\\feisi\\FileWriterDemo.txt",true);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        BufferedWriter bw = new BufferedWriter(osw);
        //BufferedWriter bw = new BufferedWriter(new OutputStream(new FileoutputSream("D:\\feisi\\FileWriterDemo.txt"));
        bw.write("hello,world");
        bw.flush();
        bw.close();//关闭最外层
    }
}
​

本文参考文章链接:
https://blog.csdn.net/qq_44715943/article/details/116501936
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值