目录
1 File类的使用
1.1 File类概述
java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关
File 能新建、删除、重命名文件和目录,但 File 不能访问文件内容本身。 如果需要访问文件内容本身,则需要使用输入/输出流
想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录
File对象可以作为参数传递给流的构造器
1.2 File类的常用构造器
- 相对路径与绝对路径
相对路径:相较于某个路径下,指明的路径
绝对路径:包含盘符在内的文件或文件目录的路径 - 对于路径的分割符号
window:\
unix:/
@Test
public void test1(){
//构造器1
File file1 = new File("hello.txt");//相对于当前的module
File file2 = new File("D:\\ideaworkspace\\SeniorJava\\day08\\he.txt");
System.out.println(file1);
System.out.println(file2);
//构造器2
File file3 = new File("D:\\ideaworkspace","SeniorJava");
System.out.println(file3);
//构造器3
File file4 = new File(file3,"hi.txt");
}
1.3File的常用方法
- 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数组
@Test
public void test2(){
File file1 = new File("hello.txt");
File file2 = new File("D:\\IO\\hi.txt");
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getPath());
System.out.println(file1.getName());
System.out.println(file1.getParent());
System.out.println(file1.length());
System.out.println(new Date(file1.lastModified()));
System.out.println();
System.out.println(file2.getAbsolutePath());
System.out.println(file2.getPath());
System.out.println(file2.getName());
System.out.println(file2.getParent());
System.out.println(file2.length());
System.out.println(file2.lastModified());
}
@Test
public void test3(){
File file = new File("D:\\ideaworkspace\\SeniorJava");
String[] list = file.list();
for (String s : list){
System.out.println(s);
}
System.out.println();
File[] files = file.listFiles();
for(File f: files){
System.out.println(f);
}
}
- rename()方法
比如:file1.renameTo(file2)为例:
要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在
@Test
public void test4(){
File file1 = new File("hello.txt");
File file2 = new File("D:\\IO\\hi.txt");
boolean b = file1.renameTo(file2);
System.out.println(b);
}
- public boolean isDirectory():判断是否是文件目录
- public boolean isFile() :判断是否是文件
- public boolean exists() :判断是否存在
- public boolean canRead() :判断是否可读
- public boolean canWrite() :判断是否可写
- public boolean isHidden() :判断是否隐藏
@Test
public void test5(){
File file = new File("hello.txt");
System.out.println(file.isDirectory());
System.out.println(file.isFile());
System.out.println(file.exists());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.isHidden());
System.out.println();
File file1 = new File("D:\\IO");
System.out.println(file1.isDirectory());
System.out.println(file1.isFile());
System.out.println(file1.exists());
System.out.println(file1.canRead());
System.out.println(file1.canWrite());
System.out.println(file1.isHidden());
}
创建硬盘中对应的文件或文件目录
- public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
- public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
- public boolean mkdirs() :创建文件目录。如果此文件目录存在,就不创建了。如果上层文件目录不存在,一并创建
删除磁盘中的文件或文件目录
- public boolean delete():删除文件或者文件夹
删除注意事项:Java中的删除不走回收站。
@Test
public void test6() throws IOException {
//文件的创建
File file = new File("hi.txt");
if(!file.exists()){
file.createNewFile();
System.out.println("创建成功");
}else {//文件存在
file.delete();
System.out.println("删除成功");
}
}
@Test
public void test7(){
//文件目录的创建
File file1 = new File("D:\\IO\\IO1");
boolean mkdir = file1.mkdir();
if(mkdir){
System.out.println("创建成功1");
}
File file2 = new File("D:\\IO\\IO2");
boolean mkdirs = file2.mkdirs();
if(mkdirs){
System.out.println("创建成功2");
}
}
2 IO流原理及流的分类
2.1 IO流原理
I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。
Java程序中,对于数据的输入/输出操作以** “流(stream)” ** 的方式进行
输入和输出的概念(针对程序的内存而言的)
输入input:读取外部数据(磁 盘、光盘等存储设备的数据)到 程序(内存)中
输出output:将程序(内存) 数据输出到磁盘、光盘等存储设 备中。
2.2 流的分类
按操作数据单位不同分为:字节流(8 bit),字符流(16 bit)
按数据流的流向不同分为:输入流,输出流
按流的角色的不同分为:节点流,处理流
2.3 流的体系结构
3 节点流(文件流)
3.1 字符输入流(FileReader)
将hello.txt的文本内容读入程序中,并输出到控制台
//对read()操作升级:使用重载方法
@Test
public void testFileReader1() {
FileReader fr = null;
try {
//1.File类实例化
File file = new File("hello.txt");
//2.FileReader流的实例化
fr = new FileReader(file);
//3.读入的操作
char[] cbuf = new char[5];
int len;
while((len=fr.read(cbuf)) != -1){
//方式一:
//错误的写法
// for (int i = 0; i < cbuf.length; i++) {
// System.out.println(cbuf[i]);
// }
//正确的写法
// for (int i = 0; i < len; i++) {
// System.out.print(cbuf[i]);
// }
//方式二;
//错误的写法,对应方式一
// String str = new String(cbuf);
// System.out.print(str);
//正确的写法
String str = new String(cbuf,0,len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
//4.资源的关闭
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.2 字符输出流(FileWrite)
@Test
public void testFileWirte(){
FileWriter fw = null;
try {
//1.提供File类的对象,指明写出到文件
File file = new File("hello1.txt");
//2.提供FileWirte的对象,用于数据的写出
fw = new FileWriter(file);
//3.写出的操作
fw.write("I have a dream\n");
fw.write("you need have to dream");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fw != null){
//4.流资源的关闭
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.3 字节输入流(FileInputStream)与字节输出流(FileOuputStream)
//使用字节流FileInputStream处理字节流文件
@Test
public void test1() {
FileInputStream fis = null;
try {
//1造文件
File file = new File("hello.txt");
//2.造流
fis = new FileInputStream(file);
//3.读取数据
byte[] buffer = new byte[5];
int len; // 记录每次读取的字节数
while((len = fis.read(buffer)) != -1){
String str = new String(buffer,0,len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.关闭资源
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
实现对图片的复制
*/
@Test
public void test2(){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File scrfile = new File("test.jpg");
File destfile = new File("test1.jpg");
fis = new FileInputStream(scrfile);
fos = new FileOutputStream(destfile);
byte[] buffer = new byte[5];
int len;
while((len = fis.read(buffer)) != -1){
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
实现指定路径下的操作
*/
public void copyFile(String srcPath, String destPath){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File scrfile = new File(srcPath);
File destfile = new File(destPath);
fis = new FileInputStream(scrfile);
fos = new FileOutputStream(destfile);
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1){
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testCopyFile(){
long start = System.currentTimeMillis();
String srcPath = "C:\\Users\\wuzec\\Desktop\\视频1.avi";
String destPath = "C:\\Users\\wuzec\\Desktop\\视频2.avi";
copyFile(srcPath,destPath);
long end = System.currentTimeMillis();
System.out.println("复制操作花费的时间为:" + (end - start));
}
4 处理流之一:缓冲流
4.1缓冲流简介
- 为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区。
- 缓冲流要嵌套在相应的节点流上
BufferedInputStream 和BufferedInputStream
BufferedReader 和 BufferedWriter - 当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区
- 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满, BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法 flush()可以强制将缓冲区的内容全部写入输出流
- flush()方法的使用:手动将buffer中内容写入文件
4.2 缓冲流的使用
package com.wzc.java;
import org.junit.Test;
import java.io.*;
public class BufferedTest {
@Test
public void test1(){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcfile = new File("test.jpg");
File destfile = new File("test2.jpg");
//2.造流
//2.1造节点流
FileInputStream fis = new FileInputStream(srcfile);
FileOutputStream fos = new FileOutputStream(destfile);
//2.2造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节
byte[] buffer = new byte[10];
int len;
while ((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//说明:关闭外层流的同时,内层流也自动进行关闭
// fos.close();
// fis.close();
}
@Test
public void test2(){
BufferedReader br = null;
BufferedWriter bw = null;
try {
//创建文件和相应的流
br = new BufferedReader(new FileReader(new File("dbcp.txt")));
bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));
//读写操作
//方式一
// char[] cbuf = new char[1024];
// int len;
// while((len = br.read(cbuf)) != -1){
// bw.write(cbuf,0,len);
// bw.flush();
// }
//方式二
String data;
while((data = br.readLine()) != null){
//方法一
// bw.write(data + "\n"); //data中不包含换行符号
//方法二:
bw.write(data);//data中不包含换行符
bw.newLine();//提供换行操作
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
if(bw != null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
5 处理流之二:转换流
5.1 转换流简介
- 转换流提供了在字节流和字符流之间的转换
- 两种转换流:
InputStreamReader:将InputStream转换为Reader (将字节的输入流按指定字符集转换为字符的输入流)
OutputStreamWriter:将Writer转换为OutputStream(实现将字符的输出流按指定字符集转换为字节的输出流)
- 字节流中的数据都是字符时,转成字符流操作更高效
- 很多时候我们使用转换流来处理文件乱码问题。实现编码和 解码的功能
5.2 转换流的使用
import org.junit.Test;
import java.io.*;
public class InputStreamReaderTest {
@Test
public void test1() throws IOException {
/*
此时处理异常的话,仍应该使用try-catch-finally
InputStreamReader的使用,实现了字节的输入流到字符的输入流的转换
*/
FileInputStream fis = new FileInputStream("dbcp.txt");
// InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符
//参数二指明了字符集,具体使用哪个字符集,取决于文件dbcp.txt保存时使用的字符集
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1){
String str = new String(cbuf,0,len);
System.out.print(str);
}
isr.close();
}
@Test
public void test2() throws IOException {
/*
此时处理异常的话,仍应该使用try-catch-finally
*/
//1.造文件造流
FileInputStream fis = new FileInputStream("dbcp.txt");
FileOutputStream fos = new FileOutputStream("dbcp_gbk.txt");
InputStreamReader isr = new InputStreamReader(fis,"utf-8");
OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
//2.读写过程
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf)) != -1){
osw.write(cbuf,0,len);
}
//3.关闭资源
osw.close();
isr.close();
}
}
5.3 编码解码的解释
编码:字符串–>字节数组
解码:字节数组–>字符串
6 标准的输入输出流
6.1 标准输入输出流简介
- System.in和System.out分别代表了系统标准的输入和输出设备
- System.in的类型是InputStream
- 通过System类的setIn,setOut方法对默认设备进行改变。
public static void setIn(InputStream in)
public static void setOut(PrintStream out)
6.2 标准输入输出流使用
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class OtherStreamTest {
/*
1.标准的输入输出流
1.1
System.in:标准的输入流,默认从键盘输入
System.out:标准的输出流,默认从控制台输出
1.2
System类的setIn(InputStream is) / setOut(PrintStream ps)方式重现指定输入和输出流
*/
public static void main(String[] args) {
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
while(true){
System.out.println("请输入字符串:");
String data = br.readLine();
if("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)){
System.out.println("程序结束");
break;
}
String upperCase = data.toUpperCase();
System.out.println(upperCase);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
7 打印流
7.1 打印流简介
- 实现将基本数据类型的数据格式转化为字符串输出
8 数据流
8.1 数据流简介
- 为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。
- DataInputStream 和 DataOutputStream 分别“套接”在 InputStream 和 OutputStream 子类的流上
8.2 数据流的使用
/*
3.数据流
注意:处理异常的话应该使用try-catch-finally
*/
@Test
public void test3() throws IOException{
//1
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
//2
dos.writeUTF("刘某");
dos.flush();//刷新操作,将内存中的数据写入文件
dos.writeInt(123);
dos.flush();
dos.writeBoolean(true);
dos.flush();
//3.
dos.close();
}
/*
将文件中存储的 基本数据类型和字符串读取到内存中,保存在变量中
注意:读取不同类型的数据要与当初写入文件时保持一致
*/
@Test
public void test4() throws IOException{
//1.
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
//2.
String name = dis.readUTF();
int age = dis.readInt();
boolean isMale = dis.readBoolean();
System.out.println("name = " + name);
System.out.println("age = " + age);
System.out.println("isMale = " + isMale);
//3.
dis.close();
}
9 对象流
9.1 对象流简介
- ObjectInputStream和OjbectOutputSteam
用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可 以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。 - 序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
- 反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
- ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
9.2 对象的序列化机制
- 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从 而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传 输到另一个网络节点。当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
- 序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据, 使其在保存和传输时可被还原
9.3 对象流的使用
import org.junit.Test;
import java.io.*;
public class ObjectInputOutputStreamTest {
/*
序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
序列化:使用ObjectOutputStream实现
*/
@Test
public void test1(){
ObjectOutputStream oos = null;
try {
//1
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
//2
oos.writeObject(new String("没那么简单"));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos != null){
try {
//3
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
反序列化:将磁盘文件中的对象还原为内存中的一个java对象
使用ObjectInputStream
*/
@Test
public void test2(){
ObjectInputStream ois = null;
try {
//1
ois = new ObjectInputStream(new FileInputStream("object.dat"));
//2
Object obj = ois.readObject();
String str = (String) obj;
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois != null){
try {
//3
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
9.4 自定义类的序列化
- 如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可 序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一。 否则,会抛出NotSerializableException异常
- 凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:
private static final long serialVersionUID;
serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象 进行版本控制,有关各版本反序列化时是否兼容。
如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自 动生成的。若类的实例变量做了修改,serialVersionUID 可能发生变化。故建议, 显式声明。 - 简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验 证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的 serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同 就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异 常。(InvalidCastException)
Person.java
import java.io.Serializable;
/*
Person需要满足如下的要求,方可序列化
1.需要实现接口:Serializable
2.当前类提供一个全局常量:serialVersionUID
3.除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性
也必须是可序列化的。(默认情况下,基本数据类型可序列化)
*/
public class Person implements Serializable {
private String name;
private int age;
private static final long serialVersionUID = -64546456576590L;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Test.java:
import org.junit.Test;
import java.io.*;
public class ObjectInputOutputStreamTest {
/*
序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
序列化:使用ObjectOutputStream实现
*/
@Test
public void test1(){
ObjectOutputStream oos = null;
try {
//1
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
//2
oos.writeObject(new String("没那么简单"));
oos.flush();
oos.writeObject(new Person("Tom",12));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos != null){
try {
//3
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
反序列化:将磁盘文件中的对象还原为内存中的一个java对象
使用ObjectInputStream
*/
@Test
public void test2(){
ObjectInputStream ois = null;
try {
//1
ois = new ObjectInputStream(new FileInputStream("object.dat"));
//2
Object obj = ois.readObject();
String str = (String) obj;
Person p = (Person) ois.readObject();
System.out.println(str);
System.out.println(p);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois != null){
try {
//3
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
10 随机存取文件流
10.1 随机存取文件流简介
- RandomAccessFile 声明在java.io包下,但直接继承于java.lang.Object类。并 且它实现了DataInput、DataOutput这两个接口,也就意味着这个类既可以读也可以写
- RandomAccessFile 类支持 “随机访问” 的方式,程序可以直接跳到文件的任意 地方来读、写文件
支持只访问文件的部分内容
可以向已存在的文件后追加内 - 访问格式:
10.2 随机存取文件的使用
1.RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
2.RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
3.如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)
4. 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileTest {
@Test
public void test1(){
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
//1
raf1 = new RandomAccessFile(new File("test.jpg"),"r");
raf2 = new RandomAccessFile(new File("test1.jpg"),"rw");
//2
byte[] buffer = new byte[1024];
int len;
while((len = raf1.read(buffer)) != -1){
raf2.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//3
if(raf2 != null){
try {
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(raf1 != null){
try {
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void test2() throws IOException {
RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");
raf1.seek(3);//将指针调到角标为3的位置
raf1.write("xyz".getBytes());
raf1.close();
}
/*
使用RandomAccessFile实现数据的插入效果
*/
@Test
public void test3() throws IOException {
RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");
raf1.seek(3); //将指针的角标标为3的位置
//保存指针3后面的所有数据到StringBUdiler中
StringBuilder builder = new StringBuilder((int)new File("hello.txt").length());
byte[] buffer = new byte[20];
int len;
while ((len = raf1.read(buffer)) != -1){
builder.append(new String(buffer,0,len));
}
//调回指针,写入"xyz"
raf1.seek(3);
raf1.write("xyz".getBytes());
//将StringBuffer中的数据写入到文件中
raf1.write(builder.toString().getBytes());
raf1.close();
}
}
本节练习
ex1
利用File构造器,new 一个文件目录file
1)在其中创建多个文件和目录
2)编写方法,实现删除file中指定文件的操作
@Test
public void test1() throws IOException {
File file = new File("D:\\IO\\IO1\\hello.txt");
//创建一个与file同目录下的另一个文件,名为haha.txt
File destfile = new File(file.getParent(),"haha.txt");
boolean newFile = destfile.createNewFile();
if(newFile){
System.out.println("创建成功! ");
}
}
@Test
public void test2(){
File file = new File("D:\\IO\\IO1\\hello.txt");
if(file.exists()){
file.delete();
System.out.println("删除成功");
}else{
System.out.println("不存在该文件");
}
}
ex2
判断指定目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称
ex3
遍历指定目录所有文件名称,包括子文件目录中的文件。
拓展1:并计算指定目录占用空间的大小
拓展2:删除指定文件目录及其下的所有文件
ex4
分别使用节点流:FileInputStream、FileOutputStream和缓冲流: BufferedInputStream、BufferedOutputStream实现文本文件/图片/视频文件的 复制。并比较二者在数据复制方面的效率
import org.junit.Test;
import java.io.*;
public class Ex4 {
@Test
public void testCopyFile(){
String srcPath = "C:\\Users\\wuzec\\Desktop\\test.mp4";
String destPath = "C:\\Users\\wuzec\\Desktop\\test1.mp4";
String destPath1 = "C:\\Users\\wuzec\\Desktop\\test2.mp4";
long start = System.currentTimeMillis();
CopyFile(srcPath,destPath);
long end = System.currentTimeMillis();
System.out.println("不使用buffer流复制花费的时间" + (end - start));
long start1 = System.currentTimeMillis();
CopyFile_Buffer(srcPath,destPath1);
long end1 = System.currentTimeMillis();
System.out.println("使用buffer流复制花费的时间" + (end1 - start1));
}
public void CopyFile(String srcPath, String destPath){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File srcfile = new File(srcPath);
File destfile = new File(destPath);
fis = new FileInputStream(srcfile);
fos = new FileOutputStream(destfile);
byte[] bufe = new byte[1024];
int len;
while((len = fis.read(bufe)) != -1) {
fos.write(bufe,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos !=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void CopyFile_Buffer(String srcPath, String destPath){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(new File(srcPath)));
bos = new BufferedOutputStream(new FileOutputStream(new File(destPath)));
byte[] cbuf = new byte[1024];
int len;
while((len = bis.read(cbuf)) != -1){
bos.write(cbuf);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
ex5
实现图片加密操作。
import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Ex2 {
// 照片的加密
@Test
public void test1(){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("test.jpg");
fos = new FileOutputStream("test_srect.jpg");
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1){
for (int i = 0; i < len; i++) {
buffer[i] = (byte) (buffer[i] ^ 5);
}
fos.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 照片的解密
@Test
public void test2(){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("test_srect.jpg");
fos = new FileOutputStream("test_reall.jpg");
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1){
for (int i = 0; i < len; i++) {
buffer[i] = (byte) (buffer[i] ^ 5);
}
fos.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
ex6
获取文本上没个字符上出现的次数
参考资料:
[1]尚硅谷宋康红java基础教程