1.IO
首先呢IO由Input (输入流)和Output(输出流)组成简称IO
下面来看看这张图
我们可以看出IO主要分为字节流和字符流它们都有自己的输入输出流,当然还有其他的流:缓冲流、字节流转为字符流、数据流等,这些流就可以完成我们文件的操作比如:复制,剪切,删除等操作。
2.学IO前必掌握的File(文件)类的使用方法
创建文件
File file = new File("E:\\QQPCmgr\\Desktop\\新建文本文档.txt");
// 文件是否存在
System.out.println(file.exists());
// file对象的文件能否执行
System.out.println(file.canExecute());
// 如果没有创建文件
if (!file.exists()) {
file.createNewFile();
}
// // 如果有删除文件
// if(file.exists()) {
//
// file.delete();
// }
// 获取file对象指向的文件的全路径
System.out.println(file.getAbsolutePath());
// 获取文件名
System.out.println(file.getName());
// 获取上级目录对应的file对象
File p = file.getParentFile();
System.out.println(p);
System.out.println(file.getPath());
// 判断file对象是否指向的是一个文件夹
System.out.println(file.isDirectory());
// 判断file对象是否指向的是一个文件
System.out.println(file.isFile());
// 判断是否隐藏文件
System.out.println(file.isHidden());
// 查看文件最后的修改时间
System.out.println(file.lastModified());
// 获取文件的长度
System.out.println(file.length());
// 获取file指向的文件夹所有的文件和文件夹
System.out.println("=======");
File[] files = file.listFiles();
// for(File f:files) {
// System.out.println(f);
// }
//
// 创建文件夹,如果父文件夹不存在,也创建
file.mkdirs();
// renameTo是一个剪切并重命名的效果00
File f1 = new File("E:\\\\QQPCmgr\\\\Desktop\\新建.txt");
file.renameTo(f1);
3.IO的输入流使用方法
Reader r = null;
try {
// 创建了一个输入流
r = new FileReader("");
char[] c = new char[2];
StringBuilder sb = new StringBuilder();
while (true) {
// read方法用于读取文件内容,返回值是读取的长度,读取的内容存到传入数组中。
int len = r.read(c);
if (len == -1) {
break;
}
// 创建字符串时只需要读取的长度个
String s = new String(c, 0, len);
sb.append(s);
}
System.out.println(sb.toString());
} catch (Exception e) {
// e.printStackTrace();
} finally {
try {
r.close();
} catch (Exception e) {
// e.printStackTrace();
}
}
4.IO的输出流使用方法
String src = "我很帅但我很温柔。";
Writer w = null;
try {
// 创建一个输出流対象
w = new FileWriter("");// 写出内容
w.write(src);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
w.close();
} catch (Exception e) {
e.printStackTrace();
}
}
5.复制文件(结合输入流和输出流)
Reader r = null;
Writer w = null;
try {
r = new FileReader("");
w = new FileWriter("");
char[] c = new char[2];
int len;
while ((len = r.read(c)) != -1) {
w.write(c, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
w.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
r.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}