IO编程
静听花开花落,坐看云卷云舒
一切属于IO流都要进行关闭操作
1. File文件操作
文件的分隔符:File.separator;
方法 | 类型 | 说明 |
---|---|---|
public File(String pathName) | 构造 | 操作文件的完整路径 |
public File(File parent,String child) | 构造 | 操作文件的父路径和文件的名称 |
public boolean createNewFile() throws Exception | 普通 | 创建文件 |
public boolean delete() | 普通 | 删除文件 |
public boolean exists() | 普通 | 文件是否存在 |
public File getParentFile() | 普通 | 找到文件的父路径 |
public boolean mkdirs() | 普通 | 创建指定路径 |
public boolean canRead() | 普通 | 文件是否可读 |
public boolean canWrite() | 普通 | 文件是否可写 |
public boolean canExecute() | 普通 | 文件是否可执行 |
public long length() | 普通 | 获取文件大小(字节) |
public boolean isDirectory() | 普通 | 是否是目录 |
public boolean isFile() | 普通 | 是否是文件 |
public boolean isHidden() | 普通 | 是否隐藏 |
public File[] listFiles() | 普通 | 列出目录中的全部文件信息 |
- 栗子1:
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class File1 {
public static double round(double num,int scale) {
return Math.round(Math.pow(10,scale) * num) / Math.pow(10,scale);
}
public static void main(String[] args) throws Exception {
File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file.exists()) {
System.out.println("文件是否可读:" + file.canRead());
System.out.println("文件是否可写:" + file.canWrite());
System.out.println("文件是否可执行:" + file.canExecute());
System.out.println("文件大小:" + File1.round(file.length() / (double)1024 / 1024,2) + "M");
System.out.println("最后的修改时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified())));
System.out.println("是目录:" + file.isDirectory());
System.out.println("是文件:" + file.isFile());
System.out.println("是否隐藏" + file.isHidden());
file.delete();
System.out.println("文件删除成功!");
} else {
file.createNewFile();
System.out.println("文件创建成功");
System.out.println("文件是否可读:" + file.canRead());
System.out.println("文件是否可写:" + file.canWrite());
System.out.println("文件是否可执行:" + file.canExecute());
System.out.println("文件大小:" + File1.round(file.length() / (double)1024 / 1024,2) + "M");
System.out.println("最后的修改时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified())));
System.out.println("是目录:" + file.isDirectory());
System.out.println("是文件:" + file.isFile());
System.out.println("是否隐藏" + file.isHidden());
}
}
}
- 栗子2:
import java.io.File;
public class File2 {
public static void main(String[] args) {
File file = new File("D:" + File.separator + "test");
listDir(file);
}
private static void listDir(File file) {
//目录进行遍历,文件进行重命名
if (file.isDirectory()) {
File result[] = file.listFiles();
if (result != null) {
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
} else {
if (file.isFile()) {
String fileName = null;
if (file.getName().endsWith(".txt")) {
fileName = file.getName().substring(0,file.getName().lastIndexOf(".")) + ".java";
File newFile = new File(file.getParentFile(),fileName);
file.renameTo(newFile);
}
}
}
}
}
2. 字节输出流(OutputStream)
程序需要读取数据(读)时,利用输入流完成,程序需要将数据保存到数据(写)时,需要输出流
public abstract class OutputStream extends Object implements Closeable, Flushable {}
- Closeable接口
public interface Closeable extends AutoCloseable {
void close() throws IOException;
}
- Flushable接口
public interface Flushable {
void flush() throws IOException;
}
方法 | 类型 | 说明 |
---|---|---|
public abstract void write(int b) throws IOException | 普通 | 输出单个字节数据 |
public void write(byte[] b) throws IOException | 普通 | 输出一组字节数据 |
public void write(byte[] b,int off,int len) throws IOException | 普通 | 输出部分字节数据 |
public void close() throws IOException | 普通 | 关闭输出流 |
public void flush() throws IOException | 普通 | 刷新缓冲区 |
主要目的为OutputStream父类实例化
方法 | 类型 | 说明 |
---|---|---|
public FileOutputStream(File file) throws FileNotFoundException | 构造 | 采用覆盖的形式创建文件输出流 |
public FileOutputStream(File file,boolean append) throws FileNotFoundException | 构造 | 采用覆盖或者追加的形式创建文件输出流 |
- 栗子:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class OutputStream1 {
public static void main(String[] args) throws Exception {
File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream output = new FileOutputStream(file,true);
String str = "hdhf\r\n";
output.write(str.getBytes());
output.flush();
output.close();
}
}
3. 字节输入流(InputStream)
程序读取的时候需要输入
public abstract class InputStream extends Object implements Closeable {}
方法 | 类型 | 说明 |
---|---|---|
public abstract int read throws IOException | 普通 | 读取单个字节数据,如果现在已经读取到底了,返回-1 |
public int read(byte[] var1) throws IOException | 普通 | 读取一组字节数据,返回的是读取的个数;如果没有数据,且已经读取到底则返回-1 |
public int read(byte[] var1, int var2, int var3) throws IOException | 普通 | 读取一组字节数据,只占数组的部分 |
public void close() throws IOException | 普通 | 关闭输入流 |
public byte[] readAllBytes() throws IOException | 普通 | 读取输入流的全部字节数据,jdk1.9后新增 |
public long transferTo(OutputStream out) throws IOException | 普通 | 输入流转存到输出流,jdk1.9后新增 |
栗子:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class InputStream1 {
public static void main(String[] args) throws Exception {
File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
if (file.exists()) {
InputStream input = new FileInputStream(file);
byte[] data = new byte [1024];
int len = input.read(data);
/* byte data [] = input.readAllBytes();*///jdk1.9后新增
System.out.println(new String(data,0,data.length));
input.close();
}
}
}
4. 字符输出流(Writer)
方便中文的输出和写入
public abstract class Writer implements Appendable, Closeable, Flushable{}
- Appendable接口
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package java.lang;
import java.io.IOException;
public interface Appendable {
Appendable append(CharSequence var1) throws IOException;
Appendable append(CharSequence var1, int var2, int var3) throws IOException;
Appendable append(char var1) throws IOException;
}
方法 | 类型 | 说明 |
---|---|---|
public void write(int var1) throws IOException | 普通 | 输出单个字符 |
public void write(char[] var1) throws IOException | 普通 | 输出字符数组 |
public void write(String var1) throws IOException | 普通 | 输出字符串 |
public Writer append(CharSequence var1) throws IOException | 普通 | 追加输出内容 |
public abstract void flush() throws IOException | 普通 | 刷新缓冲区 |
public abstract void close() throws IOException | 普通 | 关闭输出流 |
方法 | 类型 | 说明 |
---|---|---|
public FileWriter(File var1) throws IOException | 普通 | 采用覆盖的形式创建文件输出流 |
public FileWriter(File var1, boolean var2) throws IOException | 普通 | 采用覆盖或追加的形式创建文件输出流 |
- 栗子:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class Writer1 {
public static void main(String[] args) throws IOException {
File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
Writer out = new FileWriter(file);
out.write("dhhd");
out.append("djhfhh");
out.flush();//特别注意,没有也能输出是因为close()强制刷新
out.close();
}
}
5. 字符输入流(Reader)
方便中文的输入和读
public abstract class Reader implements Readable, Closeable {}
- Readable接口
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package java.lang;
import java.io.IOException;
import java.nio.CharBuffer;
public interface Readable {
int read(CharBuffer var1) throws IOException;
}
方法 | 类型 | 说明 |
---|---|---|
public int read() throws IOException | 普通 | 读取单个字符,无数据读取时返回-1 |
public int read(char[] var1) throws IOException | 普通 | 读取多个字符,并且返回读取个数 |
public long skip(long var1) throws IOException | 普通 | 跳过指定的字符个数后读取 |
public boolean ready() throws IOException | 普通 | 是否可以开始读取数据 |
public abstract void close() throws IOException | 普通 | 关闭输入流 |
- 栗子
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
public class Reader1 {
public static void main(String[] args) throws Exception {
File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
if (file.exists()) {
Reader reader = new FileReader(file);
char[] data = new char[1024];
reader.skip(2);
int len = reader.read(data);
System.out.println(new String(data,0,len));
reader.close();
}
}
}
6. 字节流与字符流区别,转换流
字节流直接进行数据处理操作,字符流使用了缓冲区
- 转换流栗子:
import java.io.*;
public class OutputStream1 {
public static void main(String[] args) throws Exception {
File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream output = new FileOutputStream(file,true);
Writer out = new OutputStreamWriter(output);
/* String str = "hdhf\r\n";
output.write(str.getBytes());*/
out.append("djhhbdfhl");
output.flush();
out.flush();
output.close();
out.close();
}
}
7. 内存操作流
一般用于BIO
字节内存操作流:ByteArrayInputStream,ByteArrayOutputStream
- ByteArrayInputStream类
public class ByteArrayInputStream extends InputStream {}
- ByteArrayOutputStream
public class ByteArrayOutputStream extends OutputStream {}
字符内存操作流:CharArrayReader,CharArrayWriter
- CharArrayReader
public class CharArrayReader extends Reader {}
- CharArrayWriter
public class CharArrayWriter extends Writer {}
8. 管道流
一般用于NIO
管道输出流:PipedOutputStream,PipedWriter
- PipedOutputStream
public class PipedOutputStream extends OutputStream {}
- PipedWriter
public class PipedWriter extends Writer {}
管道输入流:PipedInputStream,PipedReader
- PipedInputStream
public class PipedInputStream extends InputStream {}
- PipedReader
public class PipedReader extends Reader {}
9. 打印流
解决字节和字符输出流的局限性
public class PrintWriter extends Writer {}
- 栗子:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class PrintWriter1 {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
PrintWriter pu = new PrintWriter(new FileOutputStream(file));
pu.println("姓名:djhj");
pu.print("年龄:");
pu.print(15);
pu.close();
}
}
10. 缓冲输入流(BufferedReader)
字符流的缓冲区数据读取
方法 | 类型 | 说明 |
---|---|---|
public BufferedReader(Reader var1) | 构造 | 接受一个Reader类的实例 |
public String readLine() throws IOException | 普通 | 一次性从缓冲区中将内容全部读取进来 |
- 栗子
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferedReader1 {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入您的年龄:");
String msg = input.readLine();
if (msg.matches("\\d{1,3}")) {
int age = Integer.parseInt(msg);
System.out.println("年龄为:" + age);
} else {
System.out.println("输入的不是数字");
}
input.close();
}
}
11. 对象序列化
把一个对象变为二进制的数据流的方法,必须实现Serializable接口,不能序列化关键字 transient
方法 | 类型 | 说明 |
---|---|---|
public ObjectOutputStream(OutputStream var1) throws IOException | 构造 | 传入输入的对象 |
public final void writeObject(Object var1) throws IOException | 普通 | 输出对象 |
方法 | 类型 | 说明 |
---|---|---|
public ObjectInputStream(InputStream var1) throws IOException | 构造 | 构造输入对象 |
public final Object readObject() throws IOException, ClassNotFoundException { | 普通 | 从指定位置读取对象 |
- 栗子
import java.io.Serializable;
@SuppressWarnings("serial") //序列化编号自动生成
public class Member implements Serializable {
private transient String memberId;//不能被序列化
private String name;
private int age;
public Member(String memberId, String name, int age) {
this.memberId = memberId;
this.name = name;
this.age = age;
}
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
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 "Member{" +
"memberId='" + memberId + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
- 对象序列化与反序列化
import java.io.*;
public class JavaIODemo {
private static final File SAVE_FILE = new File("D:" + File.separator + "test" + File.separator + "t.txt");
public static void main(String[] args) throws IOException, ClassNotFoundException {
savaObject(new Member("11","lisi",99));
System.out.println(loadObject());
}
//序列化
private static void savaObject(Member lisi) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SAVE_FILE));
oos.writeObject(lisi);
oos.close();
}
//反序列化
private static Object loadObject() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SAVE_FILE));
Object obj = ois.readObject();
ois.close();
return obj;
}
}
12. 总结
总结了一些IO编程,还有一些没有在里面,欢迎在评论总结!