File类
如果希望在程序中操作文件和目录,都可以通过File类来完成
package day7;import java.io.File;
import java.io.IOException;public class FileTest {public static void main(String[] args) throws IOException {File file = new File(".");// 获取文件名System.out.println(file.getName());// 获取绝对路径System.out.println(file.getAbsolutePath());// 列出当前路径下所有的文件String[] fileList = file.list();if (fileList != null) {for (String fileName : fileList) {System.out.println(fileName);}}}
}
eg:递归遍历目录
package day7;import java.io.File;
import java.util.Scanner;/*** 递归遍历目录*/
public class FileWalk {public static void walk(String path) {File file = new File(path);File[] files = file.listFiles();if (files != null) {for (File file1 : files) {if (file1.isFile()) {System.out.println(file1.getName());} else if (file1.isDirectory()) {walk(file1.getPath());}}}}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);String path = scanner.next();walk(path);}
}
字节流和字符流
字节流操作的数据单元是字节,字符流操作的单元是字符
InputStream和Reader
package day7;import java.io.FileInputStream;
import java.io.IOException;public class FileInputStreamTest {public static void main(String[] args) throws IOException {FileInputStream inputStream = new FileInputStream("properties.txt");byte[] bytes = new byte[1024];int len;while ((len = inputStream.read(bytes)) != -1) {System.out.print(new String(bytes, 0, len));}inputStream.close();}
}
package day7;import java.io.FileReader;
import java.io.IOException;public class FileReaderTest {public static void main(String[] args) {try(FileReader fileReader = new FileReader("properties.txt")) {char[] chars = new char[32];int len;while ((len=fileReader.read(chars)) != -1) {System.out.print(new String(chars, 0, len));}} catch (IOException e) {e.printStackTrace();}}
}
OutputStream和Writer
package day7;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;/*** 文件复制*/
public class FileOutputStreamTest {public static void main(String[] args) throws IOException {// 创建字节输入流FileInputStream fileInputStream = new FileInputStream("properties.txt");// 创建字节输出流FileOutputStream fileOutputStream = new FileOutputStream("properties.bak.txt");byte[] bytes = new byte[1024];int len;while ((len = fileInputStream.read(bytes)) != -1) {fileOutputStream.write(bytes, 0, len);}fileOutputStream.close();fileInputStream.close();}
}
package day7;import java.io.FileWriter;
import java.io.IOException;public class FileWriterTest {public static void main(String[] args) throws IOException {String string = "学习贯彻习近平新时代中国特色社会主义思想是增强政治意识、大局意识、核心意识、看齐意识,维护习近平总书记党中央的核心、全党的核心地位,维护党中央权威和集中统一领导,在思想上政治上行动上同以习近平同志为核心的党中央保持高度一致的实际举措。";FileWriter fileWriter = new FileWriter("text.txt");fileWriter.write(string);fileWriter.close();}
}
如果进行输入输出的内容是文本内容,则应该考虑使用字符流
如果进行输入输出的内容是二进制内容,则应该考虑使用字节流