IO流

File类

概述

  • java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关。
  • File 能新建、删除、重命名文件和目录,但 File 不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入/输出流。
  • File对象可以作为参数传递给流的构造器。

常用构造器

  • public File(String pathname):以pathname为路径创建File对象,可以是绝对路径或者相对路径。
  • public File(String parent,String child):以parent为父路径,child为子路径创建File对象。
  • public File(File parent,String child):根据一个父File对象和子文件路径创建File对象。

常用方法

  • 获取功能:
    ①public String getAbsolutePath():获取绝对路径。
    ②public String getPath() :获取路径。
    ③public String getName() :获取名称。
    ④public String getParent():获取上层文件目录路径。若无,返回null。
    ⑤public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
    ⑥public long lastModified() :获取最后一次的修改时间,毫秒值。
    ⑦public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组。
    ⑧public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组。

  • 重命名功能:
    ①public boolean renameTo(File dest):把文件重命名为指定的文件路径。

  • 判断功能:
    ①public boolean isDirectory():判断是否是文件目录。
    ②public boolean isFile() :判断是否是文件。
    ③public boolean exists() :判断是否存在。
    ④public boolean canRead() :判断是否可读。
    ⑤public boolean canWrite() :判断是否可写。
    ⑥public boolean isHidden() :判断是否隐藏。

  • 创建功能:
    ①public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false。
    ②public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
    ③public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建。

  • 删除功能:
    ① public boolean delete():删除文件或者文件夹。

流的分类

概述

  • 按操作数据单位不同分为:字节流(8 bit) ,字符流(16 bit)。
  • 按数据流的流向不同分为:输入流,输出流。
  • 按流的角色的不同分为:节点流(直接从数据源或目的地读写数据),处理流(不直接连接到数据源或目的地,而是“连接”在已存在的节点流或处理流之上,通过对数据的处理为程序提供更为强大的读写功能)。
    在这里插入图片描述
    在这里插入图片描述在这里插入图片描述

InputStream

  • int read():从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。如果因为已经到达流末尾而没有可用的字节,则返回值 -1。
  • int read(byte[] b):从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。如果因为已经到达流末尾而没有可用的字节,则返回值 -1。否则以整数形式返回实际读取的字节数。
  • int read(byte[] b, int off, int len):将输入流中最多 len 个数据字节读入 byte 数组。尝试读取 len 个字节,但读取的字节也可能小于该值。以整数形式返回实际读取的字节数。如果因为流位于文件末尾而没有可用的字节,则返回值 -1。
  • public void close() throws IOException:关闭此输入流并释放与该流关联的所有系统资源。
  • FileInputStream 从文件系统中的某个文件中获得输入字节。FileInputStream用于读取非文本数据之类的原始字节流。要读取字符流,需要使用 FileReader。

Reader

  • int read():读取单个字符。作为整数读取的字符,范围在 0 到 65535 之间(0x00-0xffff)(2个字节的Unicode码),如果已到达流的末尾,则返回 -1。
  • int read(char[] cbuf):将字符读入数组。如果已到达流的末尾,则返回 -1。否则返回本次读取的字符数。
  • int read(char[] cbuf,int off,int len):将字符读入数组的某一部分。存到数组cbuf中,从off处开始存储,最多读len个字符。如果已到达流的末尾,则返回 -1。否则返回本次读取的字符数。
  • public void close() throws IOException:关闭此输入流并释放与该流关联的所有系统资源。

OutputStream

  • void write(int b):将指定的字节写入此输出流。write 的常规协定是:向输出流写入一个字节。要写入的字节是参数 b 的八个低位。b 的 24 个高位将被忽略。 即写入0~255范围的。
  • void write(byte[] b):将 b.length 个字节从指定的 byte 数组写入此输出流。write(b) 的常规协定是:应该与调用 write(b, 0, b.length) 的效果完全相同。
  • void write(byte[] b,int off,int len):将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
  • public void flush() throws IOException:刷新此输出流并强制写出所有缓冲的输出字节,调用此方法指示应将这些字节立即写入它们预期的目标。
  • public void close() throws IOException:关闭此输出流并释放与该流关联的所有系统资源。
  • FileOutputStream 从文件系统中的某个文件中获得输出字节。FileOutputStream用于写出非文本数据之类的原始字节流。要写出字符流,需要使用 FileWriter。

Writer

  • void write(int c):写入单个字符。要写入的字符包含在给定整数值的 16 个低位中,16 高位被忽略。 即写入0 到 65535 之间的Unicode码。
  • void write(char[] cbuf):写入字符数组。
  • void write(char[] cbuf,int off,int len):写入字符数组的某一部分。从off开始,写入len个字符。
  • void write(String str):写入字符串。
  • void write(String str,int off,int len):写入字符串的某一部分。
  • void flush():刷新该流的缓冲,则立即将它们写入预期目标。
  • public void close() throws IOException:关闭此输出流并释放与该流关联的所有系统资源。

节点流(或文件流)

  • 读取文件:
1、建立一个流对象,将已存在的一个文件加载进流。
FileReader fr = new FileReader(new File(“Test.txt”));
2、创建一个临时存放数据的数组。
char[] ch = new char[1024];
3、调用流对象的读取方法将流中的数据读入到数组中。
fr.read(ch);
4、关闭资源。
fr.close();
FileReader fr = null;
try {
	fr = new FileReader(new File("c:\\test.txt"));
    char[] buf = new char[1024];
    int len;
    while ((len = fr.read(buf)) != -1) {
    	System.out.print(new String(buf, 0, len));
    }
} catch (IOException e) {
	System.out.println("read-Exception :" + e.getMessage());
} finally {
	if (fr != null) {
    	try {
        	fr.close();
        } catch (IOException e) {
        	System.out.println("close-Exception :" + e.getMessage());
        }
    }
}
  • 写入文件:
1、创建流对象,建立数据存放文件。
FileWriter fw = new FileWriter(new File(“Test.txt”));
2、调用流对象的写入方法,将数据写入流。
fw.write(“xxx”);
3、关闭流资源,并将流中的数据清空到文件中。
fw.close();
FileWriter fw = null;
try {
	fw = new FileWriter(new File("Test.txt"));
	fw.write("xxx");
} catch (IOException e) {
	e.printStackTrace();
} finally {
	if (fw != null)
		try {
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
}

缓冲流

  • 为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区。
  • 当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区。
  • 当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192(8Kb)个字节存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。
  • 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法flush()可以强制将缓冲区的内容全部写入输出流。
  • 关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也会相应关闭内层节点流。
  • 如果是带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,关闭后不能再写出。
    在这里插入图片描述
BufferedReader br = null;
BufferedWriter bw = null;
try {
	// 创建缓冲流对象:它是处理流,是对节点流的包装
	br = new BufferedReader(new FileReader("d:\\IOTest\\source.txt"));
	bw = new BufferedWriter(new FileWriter("d:\\IOTest\\dest.txt"));
	String str;
	while ((str = br.readLine()) != null) { // 一次读取字符文本文件的一行字符
		bw.write(str); // 一次写入一行字符串
		bw.newLine(); // 写入行分隔符
	}
	bw.flush(); // 刷新缓冲区
} catch (IOException e) {
	e.printStackTrace();
} finally {
	// 关闭IO流对象
	try {
		if (bw != null) {
			bw.close();
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
	try {
		if (br != null) {
			br.close();
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}

转换流

  • 转换流提供了在字节流和字符流之间的转换。
  • Java API提供了两个转换流: InputStreamReader将InputStream 转换为Reader;OutputStreamWriter将Writer 转换为OutputStream。

InputStreamReader

  • 实现将字节的输入流按指定字符集转换为字符的输入流。
  • 需要和InputStream“套接”。
  • 构造器:
    ① public InputStreamReader(InputStream in)。
    ②public InputSreamReader(InputStream in,String charsetName)。

OutputStreamWriter

  • 实现将字符的输出流按指定字符集转换为字节的输出流。
  • 需要和OutputStream“套接”。
  • 构造器:
    ①public OutputStreamWriter(OutputStream out)。
    ②public OutputStreamWriter(OutputStream out,String charsetName)。

标准输入、输出流

  • System.in和System.out分别代表了系统标准的输入和输出设备。
  • System.in的类型是InputStream; System.out的类型是PrintStream,其是FilterOutputStream 的子类,FilterOutputStream 是OutputStream的子类。
  • 重定向:通过System类的setIn,setOut方法对默认设备进行改变。 public static void setIn(InputStream in),public static void setOut(PrintStream out)。
/**
 * 从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续
 * 进行输入操作,直至当输入“e”或者“exit”时,退出程序。
 */
System.out.println("请输入信息(退出输入e或exit):");
// 把"标准"输入流(键盘输入)这个字节流包装成字符流,再包装成缓冲流
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = null;
try {
	while ((s = br.readLine()) != null) { // 读取用户输入的一行数据 --> 阻塞程序
		if ("e".equalsIgnoreCase(s) || "exit".equalsIgnoreCase(s)) {
        	System.out.println("安全退出!!");
        	break;
        }
        // 将读取到的整行字符串转成大写输出
        System.out.println("-->:" + s.toUpperCase());
        System.out.println("继续输入信息");
    }
} catch (IOException e) {
	e.printStackTrace();
} finally {
	try {
    	if (br != null) {
        	br.close();
        }
    } catch (IOException e) {
    	e.printStackTrace();
    }
}
/**
 * 实现从键盘输入int, double, float, boolean, short, byte and String值。
 * 作用和使用下面方法一样。
 *  Scanner s = new Scanner(System.in);
 *  s.nextInt();
 *  s.next();
 */
public static String readString() {
 	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String string = "";
    try {
    	string = br.readLine();
    } catch (IOException ex) {
    	System.out.println(ex);
    }
    return string;
}
public static int readInt() {
	return Integer.parseInt(readString());
}
public static double readDouble() {
	return Double.parseDouble(readString());
}
public static double readByte() {
    return Byte.parseByte(readString());
}
public static double readShort() {
    return Short.parseShort(readString());
}
public static double readLong() {
    return Long.parseLong(readString());
}
public static double readFloat() {
    return Float.parseFloat(readString());
}

打印流

实现将基本数据类型的数据格式转化为字符串输出。

PrintStream&PrintWriter

  • 提供了一系列重载的print()和println()方法,用于多种数据类型的输出。
  • PrintStream和PrintWriter的输出不会抛出IOException异常。
  • PrintStream和PrintWriter有自动flush功能。
  • PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
  • System.out返回的是PrintStream的实例。
PrintStream ps = null;
try {
	FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
	//创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
	ps = new PrintStream(fos, true);
	if (ps != null) {// 把标准输出流(控制台输出)改成文件
		System.setOut(ps);
	}
	for (int i = 0; i <= 255; i++) { // 输出ASCII字符
		System.out.print((char) i);
		if (i % 50 == 0) { // 每50个数据一行
			System.out.println(); // 换行
		}
	}
} catch (FileNotFoundException e) {
	e.printStackTrace();
} finally {
	if (ps != null) {
		ps.close();
	}
}

数据流

  • 为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。
  • 数据流有两个类:DataInputStream 和 DataOutputStream,分别“套接”在 InputStream 和 OutputStream 子类的流上。
  • DataInputStream中的方法:
    在这里插入图片描述
  • DataOutputStream中的方法:将上述的方法的read改为相应的write即可。

对象流

用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。

ObjectInputStream&ObjectOutputStream

  • 序列化:用ObjectOutputStream类保存基本类型数据或对象的机制。
  • 反序列化:用ObjectInputStream类读取基本类型数据或对象的机制。
  • ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量。

对象的序列化

在这里插入图片描述
在这里插入图片描述在这里插入图片描述

/**
 * 序列化:将对象写入到磁盘或者进行网络传输。
 * 要求对象必须实现序列化
 */
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(“data.txt"));
Person p = new Person("韩梅梅", 18, "中华大街", new Pet());
oos.writeObject(p);
oos.flush();
oos.close();
/**
 * 反序列化:将磁盘中的对象数据源读出。
 */
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(“data.txt"));
Person p1 = (Person)ois.readObject();
System.out.println(p1.toString());
ois.close();

在这里插入图片描述

随机存取文件流

RandomAccessFile

  • RandomAccessFile 声明在java.io包下,但直接继承于java.lang.Object类。并且它实现了DataInput、DataOutput这两个接口,也就意味着这个类既可以读也可以写。
  • RandomAccessFile 类支持 “随机访问” 的方式,程序可以直接跳到文件的任意地方来 读、写文件。
  • RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。它可以自由移动记录指针:long getFilePointer()获取文件记录指针的当前位置和void seek(long pos)将文件记录指针定位到 pos 位置。
  • 构造器:public RandomAccessFile(File file, String mode)和public RandomAccessFile(String name, String mode),其中 mode 参数指
    定 RandomAccessFile 的访问模式,包括:
    在这里插入图片描述
  • 读取文件内容:
RandomAccessFile raf = new RandomAccessFile(“test.txt”, “rw”);
raf.seek(5);
byte [] b = new byte[1024];
int off = 0;
int len = 5;
raf.read(b, off, len);
String str = new String(b, 0, len);
System.out.println(str);
raf.close();
  • 写入文件内容:
RandomAccessFile raf1 = new RandomAccessFile("hello.txt", "rw");
raf1.seek(5);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[10];
int len;
while((len = raf1.read(buffer)) != -1){
	baos.write(buffer, 0, len);
}
raf1.seek(5);
raf1.write("xyz".getBytes());
raf1.write(baos.toString().getBytes());
baos.close();
raf1.close();

CommonsIO

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值