原理
体系结构
硬盘存储–文件操作
1)硬件: 处理器(cpu)、存储器(内存)、输入输入–IO
【CPU只能和内存做直接的数据交换】
2)输入: 现实中的物理信号转换为数字格式存储在内存中
3)输出: 将数字信号转为物理信号
4)常见IO设备 显示器O、触屏显示器IO、鼠标I、键盘I、摄像头I、麦克风I、扬声器O、硬盘IO、网卡IO
硬盘----存储
文件的基本知识
对文件系统树的操作–针对元数据
File类
【java.io下】
【构造方法】
public class Demo1 {
public static void main(String[] args) {
//1、绝对路径的方式创建
//1.1 直接创建
File file = new File("I:\\Desktop\\IO操作文件\\hello.txt");
//1.2 传入父路径 + 子路径
File file1 = new File("I:\\Desktop\\IO操作文件","hello.txt");
//1.3 以File 传入parent
File parent = new File("I:\\Desktop\\IO操作文件");
File file2 = new File(parent,"hello.txt");
}
}
【删除非空目录】
import java.io.File;
import java.io.IOException;
/**
* @work: dfs遍历删除 非空目录
* @Author:Mr.Kong
* @Date:Create in 15:52 2022/7/5
* @Modified By:
*/
public class Demo2 {
public static void main(String[] args) throws IOException {
File file = new File("I:\\Desktop\\IO操作文件");
Demo2 demo2 = new Demo2();
demo2.dfs(file);
}
private void dfs(File dir) throws IOException {
File[] files = dir.listFiles();//这个目录下所有孩子
for (File file1 : files) {
if (file1.isDirectory()) {//如果是目录继续深度优先遍历
System.out.println(file1.getCanonicalFile() + "\\");
dfs(file1);
//此时都是空目录
file1.delete();
} else {
System.out.println(file1.getCanonicalFile());//得到这个文件的一个标准的绝对路径
// 所谓标准的就是去除掉干扰的.或者..
file1.delete();//不是目录直接删
}
}
}
}
相对路径
【进程运行时的工作目录–cwd】
内容读写
读操作
【直接读和文本读】
【String的构造方法】
【Scanner构造方法】
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream("I:\\Desktop\\IO操作文件\\3\\hello.txt");
byte[] buf = new byte[1024];
int n = is.read(buf);//n是[0,1024)
//String构造方法读文件
String s= new String(buf,0,n,"UTF-8");
System.out.println(s);
is.close();
//Scanner构造方法读文件
try (InputStream word = new FileInputStream("I:\\Desktop\\IO操作文件\\3\\kk.txt")){
try (Scanner scanner = new Scanner(word,"UTF-8")){
while (scanner.hasNextLine()){
String line = scanner.nextLine();//默认去掉换行了
System.out.println(line);
}
}
}
}
写操作–OutputStream
【写完之后要调用flush方法】
public class Demo5 {
public static void main(String[] args) throws Exception {
//如果文件之间不存在进行创建
//创建可能失败:1、权限,2、路径上目录不存在
//如果文件之间存在进行清空后再写
try (OutputStream os = new FileOutputStream("I:\\Desktop\\IO操作文件\\3\\小丑.txt")){
os.write(110);
os.write(105);
os.flush();
}
try (OutputStream os = new FileOutputStream("I:\\Desktop\\IO操作文件\\3\\kk.txt")){
byte[] bytes =new byte[]{1,2,3,4,5,6,7,8};
os.write(bytes);
os.flush();
}
//字符写
try (OutputStream os = new FileOutputStream("I:\\Desktop\\IO操作文件\\小丑.txt")){
try (Writer writer = new OutputStreamWriter(os,"UTF-8")){
writer.write("你好中国");
writer.flush();
}
}
try (OutputStream os = new FileOutputStream("I:\\Desktop\\IO操作文件\\小丑.txt")){
try (Writer writer = new OutputStreamWriter(os,"UTF-8")){
try (PrintWriter printWriter =new PrintWriter(writer)){
printWriter.println("蝙蝠侠来了!");
}
}
}
}
}