stream
- 文件流
- Scanner
- Writer
- 遍历目录删除指定文件
- 把目标文件复制为源文件
- 小结
文件流
文件的内容本质上都是来自于硬盘,而硬盘由操作系统管理.
使用java来操作文件,就要用到java的api.
这里涉及一系列的类:
字节流: InputStream和OutputStream是以操作字节为单位(二进制文件).
字符流: Reader和Write是以操作字符为单位(文本文件)
public static void main(String[] args) throws IOException {try(InputStream inputStream = new FileInputStream("./testDir/test.txt")) {while (true) {byte[] bytes = new byte[1024];int n =inputStream.read(bytes);for (int i = 0; i < n; i++) {System.out.printf("%x ", bytes[i]);}}}}// hello file// 68 65 6c 6c 6f 20 66 69 6c 65
字节数组存储read来的字节数据.
Scanner
在操作系统中, 操作系统是一个广义的概念,System.in也是一个特殊的文件,对应标准输入.
Scanner也可以来读取文本数据,把读到的字节数据进行转换.
Scanner只适用于读文本文件, 不适合读取二进制文件.
public static void main(String[] args) throws IOException{try(InputStream inputStream = new FileInputStream("./testDir/test.txt")) {Scanner scanner = new Scanner(inputStream);String string = scanner.nextLine();System.out.println(string);}}// hello file
Writer
write之前需要打开文件,用完后也需要关闭文件.
public static void main(String[] args) throws IOException {try(Writer writer = new FileWriter("./testDir/test1.txt")) {writer.write("hello world");}}// test1.txt的内容就被修改为hello world了// 如果不想修改test1.txt的内容,使用append方法追加内容就可以了
遍历目录删除指定文件
private static Scanner scanner = new Scanner(System.in);public static void main(String[] args) {// 1.用户输入一个目录System.out.println("请输入要搜索的根目录: ");File rootPath =new File(scanner.next());// 2.用户输入要搜索或删除的关键词System.out.println("请输入要搜索或删除的关键词: ");String word = scanner.next();// 3.判断目录是否合法if(!rootPath.isDirectory()) {System.out.println("要搜索的目录不合法!!");return;}// 4.遍历目录,从根目录出发,按照深层遍历的方式遍历目录scanDir(rootPath, word);}private static void scanDir(File rootPath, String word) {// 1. 列出目录都包含哪些内容File[] files = rootPath.listFiles();if(files == null || files.length == 0) {// 不合法目录return;}// 2.遍历列出的文件,分两种情况讨论for(File f : files) {System.out.println(f.getAbsolutePath());if(f.isFile()) {// 3. 如果是普通文件,删除包含关键字的文件deleteFile(f, word);}else {// 3. 继续深层遍历scanDir(rootPath,word);}}}private static void deleteFile(File f, String word) {// 1. 判断f是否包含wordif(!f.getName().contains(word)) {return;}System.out.println("该文件是: " + f.getAbsolutePath() + "是否要删除(y/n)");String choice = scanner.next();if(choice.equals("y") || choice.equals("Y")) {f.delete();}}
会遍历根目录,找到所有包含关键字的文件,并询问是否要删除.
把目标文件复制为源文件
public static void main(String[] args) throws IOException{Scanner scanner = new Scanner(System.in);System.out.println("请输入源目标路径: ");String src = scanner.next();File srcFile = new File(src);if(!srcFile.isFile()) {System.out.println("不合法的源文件!!");return;}System.out.println("请输入目的目标路径");String dest = scanner.next();File destFile = new File(dest);if(!destFile.isFile()) {System.out.println("不合法的目标文件!!");return;}try(InputStream inputStream = new FileInputStream(srcFile);OutputStream outputStream = new FileOutputStream(destFile) ){while (true) {byte[] bytes = new byte[20480];int n = inputStream.read(bytes);if(n == -1) {System.out.println("eof");break;}outputStream.write(bytes);}}}
小结
文件流的学习到此结束了, 后面会继续 总结网络方面的知识.
有收获的小伙伴多多支持.