1、IO流
1.1 流的基本概念
流是一个抽象、动态的概念,是一连串连续动态的数据集合。
1.2 IO流的核心类
整个java.io包中最重要的就是5个类和3个接口:
类/接口 | 说明 |
---|---|
File | 文件类 |
InputStream | 字节输入流 |
OutputStream | 字节输出流 |
Reader | 字符输入流 |
Writer | 字符输出流 |
Closeable | 关闭流接口 |
Flushable | 刷新流接口 |
Serializable | 序列化接口 |
1.3 IO流的分类
根据流的方向分类:
- 输入流:数据源—》程序(InputStream、Reader,读进来)
- 输出流:程序—》数据源(OutputStream、Write,写出去)
根据功能分类:
- 节点流:可以直接从数据源或目的地读写数据。处于io操作的第一线,所有操作必须通过他们进行。
- 处理流(包装流):不能直接连接到数据源或目的地,是其他流进行包装。目的是简化操作和提高效率和性能。
根据数据类型分类:
- 字节流:按照字节读取数据(InputStream、OutputStream)。
- 字符流:按照字符读取数据(Reader、Write)。
字符流的底层也是基于字节流操作,自动搜索指定的码表。
2、File类
File类常用方法:
public class TestFile {
public static void main(String[] args) throws IOException {
//路径表示
String path = "F:\\GitHub Project\\java\\07_Java-IO\\tu.jpg";
path = "F:/GitHub Project/java/07_Java-IO/tu.jpg"; //推荐使用
//创建File对象
File file = new File(path);
file = new File("F:/GitHub Project/java/07_Java-IO/","tu.jpg");
file = new File(new File("F:/GitHub Project/java/07_Java-IO/"),"tu.jpg");
//获取基本信息
System.out.println("文件名:" + file.getName());
System.out.println("路径:" + file.getPath());
System.out.println("绝对路径:" + file.getAbsolutePath());
System.out.println("父路径:" + file.getParent());
System.out.println("文件是否存在:" + file.exists());
System.out.println("是否是文件:" + file.isFile());
System.out.println("文件是文件夹:" + file.isDirectory());
System.out.println("文件大小:" + file.length());
//创建文件
file = new File("bb.txt");
file.createNewFile();
//con为操作系统设备名,不能正确创建
file = new File("con");
file.createNewFile();
//创建文件夹
file = new File("F:/aa/bb");
boolean flag = file.mkdir(); //不会自动创建
System.out.println(flag);
flag = file.mkdirs(); //自动创建
System.out.println(flag);
//下级名称
file = new File("F:/GitHub Project/java/07_Java-IO/");
String[] str = file.list();
for(String s:str){
System.out.println(s);
}
//下级对象
File[] f = file.listFiles();
for(File fs:f){
System.out.println(fs);
}
//列出计算机所有盘符
file = new File("F:/GitHub Project/java/07_Java-IO/");
File[] f1 =file.listRoots();
for(File fs1:f1){
System.out.println(fs1);
}
}
}
案例:
案例1:获取文件夹及文件名称
public class TestDirectory {
public static void main(String[] args) {
File src = new File("F:\\GitHub Project\\java\\07_Java-IO");
printName(src,0);
}
//打印子孙级目录和文件名称
public static void printName(File src,int deep){
//控制目录层次
for (int i=0;i<deep;i++){
System.out.print("-");
}
//打印名称
System.out.println(src.getName());
if(src == null || !src.exists()){ //递归头
return;
} else if(src.isDirectory()){
for(File s:src.listFiles()){
printName(s,deep+1); //递归体
}
}
}
}
案例2:获取文件夹大小
public class TestDirectoryCount {
public static void main(String[] args) {
File src = new File("F:\\GitHub Project\\java\\07_Java-IO\\src");
count(src);
System.out.println(len);
}
//获取文件夹大小
private static long len = 0;
public static void count(File src){
if(src != null && src.exists()){
if(src.isFile()){
len+= src.length();
} else{
for (File s:src.listFiles()){
count(s);
}
}
}
}
}
3、字符集
- US-ASCII:英文ASCII。
- GBK:包含中文、日文等。
- IOS-8859-1:包含中文、日文等。
- UTF-8:变长unicode字符(1-3个字节),国际通用。
- UTF-16:定长unnicode字符(2字节)。
3.1 编码
public class TestUnicode {
public static void main(String[] args) throws UnsupportedEncodingException {
String src = "我爱你中国";
//获取字节数组
byte[] bytes = src.getBytes(); //默认utf-8
System.out.println(bytes.length); //15
//其他编码格式
bytes = src.getBytes("GBK");
System.out.println(bytes.length); //10
bytes = src.getBytes("UTF-16");
System.out.println(bytes.length); //12
}
}
3.2 解码
public class TestUnicode01 {
public static void main(String[] args) throws UnsupportedEncodingException {
String src = "我爱你中国";
byte[] bytes = src.getBytes();
//解码
src = new String(bytes,0,bytes.length,"utf-8");
System.out.println(src);
}
}
3.3 乱码的情况
- 字节数不够
- 字符集不统一
public class TestUnicode02 {
public static void main(String[] args) throws UnsupportedEncodingException {
String src = "我爱你中国";
byte[] bytes = src.getBytes();
//字节数不够
src = new String(bytes,0,bytes.length-1,"utf-8");
System.out.println(src);
//字符集不统一
src = new String(bytes,0,bytes.length-1,"gbk");
System.out.println(src);
}
}
4、创建IO流的标准步骤
- 创建源
- 选择流
- 操作
- 释放资源
public class TestIO {
public static void main(String[] args) {
//创建源
File file = new File("aa.txt");
//选择流
InputStream is = null;
try {
is = new FileInputStream(file);
//操作(读取)
int temp;
while((temp=is.read())!=-1){
System.out.println((char)temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(is != null){
//释放资源
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5、字节流
5.1 FileInputStream和FileOutputStream(文件字节流)
分段读取操作:
char[] chars = new char[1024];
int len = -1;
while ((len = reader.read(chars)) != -1) {
String str = new String(chars, 0, len);
System.out.println(str);
}
public class TestFileInputStream {
public static void main(String[] args) {
//创建源
File src = new File("aa.txt");
//选择流
InputStream is = null;
try {
is = new FileInputStream(src);
//操作(分段读取)
byte[] flush = new byte[1024]; //缓冲容器
int len = -1; //接收长度
while((len=is.read(flush))!=-1) {
String str = new String(flush,0,len); //解码
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//释放资源
if(is != null) {
is.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
写出操作:
String str = "义勇军进行曲";
char[] bytes = str.toCharArray();
writer.write(bytes,0,bytes.length);
writer.flush();
public class TestFileOutputStream {
public static void main(String[] args) {
//创建源
File dest = new File("dest.txt");
//选择流
OutputStream os = null;
try {
os = new FileOutputStream(dest,true); //内容追加
//操作(写出)
String msg = "I LOVE CHINA ";
byte[] bytes = msg.getBytes(); //编码
os.write(bytes,0,bytes.length);
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//释放资源
if(os != null) {
os.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件拷贝:
public class TestFileInputStreamAndFileOutputStream {
public static void main(String[] args) {
// 创建源
File src = new File("src.txt");
File dest = new File("src-copy.txt");
// 选择流
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(src);
os = new FileOutputStream(dest);
// 操作(分段读取)
byte[] flush = new byte[1024]; // 缓冲容器
int len = -1; // 接收长度
while ((len = is.read(flush)) != -1) {
//写入数据
os.write(flush,0,len);
os.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源(分别关闭,先打开的后关闭)
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5.2 ByteArrayInputStream和ByteArrayOutputStream(字节数组流)
public class TestByteArrayInputStream {
public static void main(String[] args) {
//创建源
byte[] src = "aa bb cc dd ee ddfdf".getBytes();
//选择流
ByteArrayInputStream bais = new ByteArrayInputStream(src);
//操作
byte[] bytes = new byte[1024];
int len = -1;
try {
while((len=bais.read(bytes))!=-1) {
String str = new String(bytes, 0, len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class TestByteArrayOutputStream {
public static void main(String[] args) {
//创建源
byte[] dest = null;
//选择流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
//操作(写出)
String str = "ByteArrayOutputStream";
byte[] bytes = str.getBytes();
baos.write(bytes, 0, bytes.length);
baos.flush();
//获取数据
dest = baos.toByteArray();
String string = new String(dest,0,dest.length);
System.out.println(string);
} catch (IOException e) {
e.printStackTrace();
}
}
}
5.3 BufferedInputStream和BufferedOutputStream(字节缓冲流)
提升性能
InputStream is = new BufferedInputStream(new FileInputStream(src));
OutputStream os = new BufferedOutputStream(new FileOutputStream(dest,true));
6、字符流
6.1 FileReader和FileWriter(文件字符流)
public class TestFileReader {
public static void main(String[] args) {
//创建源
File src = new File("src.txt");
//选择流
Reader reader = null;
try {
reader = new FileReader(src);
//操作(读取)
char[] chars = new char[1024];
int len = -1;
while ((len = reader.read(chars)) != -1) {
String str = new String(chars, 0, len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class TestFileWriter {
public static void main(String[] args) {
//创建源
File dest = new File("dest.txt");
//选择流
Writer writer = null;
try {
writer = new FileWriter(dest,true);
//操作(写出)
String str = "义勇军进行曲";
char[] bytes = str.toCharArray();
writer.write(bytes,0,bytes.length);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件拷贝:
public class TestFileReaderAndFileWriter {
public static void main(String[] args) {
//创建源
File src = new File("src.txt");
File dest = new File("src-copy1.txt");
//选择流
Reader reader = null;
Writer writer = null;
try {
reader = new FileReader(src);
writer = new FileWriter(dest);
//读取
char[] chars = new char[1024];
int len = -1;
while((len=reader.read(chars))!=-1) {
//写出
writer.write(chars, 0, len);
writer.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源(分别关闭,先打开的后关闭)
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
6.2 BufferedReader和BufferedWriter(字符缓冲流)
提升性能
Reader reader = new BufferedReader(new FileReader(src));
Writer writer = new BufferedWriter(new FileWriter(dest,true));
6.3 InputStreamReader和OutputStreamWriter(转换流)
public class TestTransformation {
public static void main(String[] args) {
/**
* 循环获取键盘输入,输出键盘输入的内容
*/
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));) {
String msg = "";
while(!msg.equals("exit")) {
msg = br.readLine();
bw.write(msg);
bw.newLine();
bw.flush();
}
} catch (Exception e) {
System.out.println("操作异常");
}
}
}
7、CommonsIO组件
组件下载:
7.1 CommonsIO组件的使用
public class TestCommonsIO {
public static void main(String[] args) throws IOException {
//获取文件及目录大小
long len = FileUtils.sizeOf(new File("src/com/bmg/io/TestFileReader.java"));
System.out.println(len);
len = FileUtils.sizeOf(new File("src/com/bmg/io"));
System.out.println(len);
//获取子孙级
Collection<File> lists = FileUtils.listFiles(new File("F:/GitHub Project/java/07_Java-IO-1"),
EmptyFileFilter.NOT_EMPTY, null);
for (File file : lists) {
System.out.println(file); //打印一层,文件不为空
}
System.out.println("*************************************************");
lists = FileUtils.listFiles(new File("F:/GitHub Project/java/07_Java-IO-1"),
FileFilterUtils.and(new SuffixFileFilter("java"),EmptyFileFilter.NOT_EMPTY), DirectoryFileFilter.INSTANCE);
for (File file : lists) {
System.out.println(file); //打印所有子孙级,文件不为空且文件后缀为java
}
//读取文件内容
String src = FileUtils.readFileToString(new File("src.txt"),"gbk");
System.out.println(src);
//逐行读取
List<String> readLines = FileUtils.readLines(new File("src.txt"),"gbk");
for (String string : readLines) {
System.out.println(string);
}
//写出文件
FileUtils.write(new File("happy.txt"), "求而不得,往往不求而得\r\n", "gbk",true);
//写出列表
List<String> list = new ArrayList<>();
list.add("马云");
list.add("雷军");
list.add("刘强东");
list.add("马化腾");
FileUtils.writeLines(new File("happy.txt"), list, "-------",true);
}
}
public class TestCommonsIO02 {
public static void main(String[] args) throws IOException {
//复制文件
FileUtils.copyFile(new File("tu.jpg"), new File("tu-copy.jpg"));
//复制文件到目录
FileUtils.copyFileToDirectory(new File("tu.jpg"), new File("lib"));
//复制目录内容
FileUtils.copyDirectory(new File("lib"), new File("lib2"));
//复制目录到目录
FileUtils.copyDirectoryToDirectory(new File("lib"), new File("lib2"));
//复制URL的内容到文件
FileUtils.copyURLToFile(new URL("http://www.baidu.com"), new File("baidu.txt"));
}
}