概述:
它是文件和目录路径名的抽象表示
对于File而言,其封装的并不是一个真正存在的文件,仅仅是一个路径名而已。它可以是存在的,也可以是不存在的。
将来是要通过具体的操作把这个路径的内容转换为具体存在的。
方法名 | 说明 |
---|---|
File(String pathname) | 通过将给定的路径名字符串转换为抽象路径名来创建新的File实例 |
File(String parent,String child) | 从父路径名字符串和子路径名字符串创建新的File实例 |
File(File parent,String child) | 从父抽象路径名和子路径名字符串创建新的File实例 |
public class FileDemo1 {
public static void main(String[] args) {
File file1 = new File("F:\\file\\java.txt");
System.out.println(file1);
File file2 = new File("F:\\file","java.txt");
System.out.println(file2);
File file3 = new File("F:\\file");
File file4 = new File(file3,"java.txt");
System.out.println(file4);
}
}
运行结果:
F:\file\java.txt
F:\file\java.txt
F:\file\java.txt
方法名 | 说明 |
---|---|
public boolean createNewFile() | 当具有该名称的文件不存在时,创建一个由该抽象路径名命名的新空文件,并返回true;存在则返回false |
public boolean mkdir() | 创建由此抽象路径命名的目录并返回true;存在则返回false |
public boolean mkdirs() | 创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录 |
public class FileDemo2 {
public static void main(String[] args) throws IOException {
File file1 = new File("F:\\file\\java.txt");
System.out.println(file1.createNewFile());
File file2 = new File("F:\\file\\JavaSE");
System.out.println(file2.mkdir());
File file3 = new File("F:\\file\\JavaWEB\\HTML");
System.out.println(file3.mkdirs());
}
}
方法名 | 说明 |
---|---|
public boolean isDirectory() | 测试此抽象路径名表示的File是否为目录 |
public boolean isFile() | 测试此抽象路径名表示的File是否为文件 |
public boolean exists() | 测试此抽象路径名表示的File是否存在 |
public String getAbsolutePath() | 返回此抽象路径名的绝对路径名字符串 |
public String getPath() | 将此抽象路径转换为路径名字符串 |
public String getName() | 返回由此抽象路径名表示的文件或者目录名称 |
public String[] list() | 返回此抽象路径名表示的目录中的文件和目录的名称字符串数组 |
public File[] listFiles() | 返回此抽象路径名表示的目录中的文件和目录的File对象数组 |
public class FileDemo3 {
public static void main(String[] args) {
File file1 = new File("F:\\file\\java.txt");
//public boolean isDirectory()测试此抽象路径名表示的File是否为目录
System.out.println(file1.isDirectory());
//public boolean isFile()测试此抽象路径名表示的File是否为文件
System.out.println(file1.isFile());
//public boolean exists()测试此抽象路径名表示的File是否存在
System.out.println(file1.exists());
//public String getAbsolutePath()返回此抽象路径名的绝对路径名字符串
System.out.println(file1.getAbsolutePath());
//public String getPath()将此抽象路径转换为路径名字符串
System.out.println(file1.getPath());
//public String getName()返回由此抽象路径名表示的文件或者目录名称
System.out.println(file1.getName());
System.out.println("---------------------");
//public String[] list()返回此抽象路径名表示的目录中的文件和目录的名称字符串数组
File file2 = new File("F:\\file");
String[] list = file2.list();
for (String s : list) {
System.out.println(s);
}
//public File[] listFiles()返回此抽象路径名表示的目录中的文件和目录的File对象数组
File[] files = file2.listFiles();
for (File file : files) {
System.out.println(file);
}
}
}
运行结果:
false
true
true
F:\file\java.txt
F:\file\java.txt
java.txt
---------------------
java.txt
JavaSE
JavaWEB
F:\file\java.txt
F:\file\JavaSE
F:\file\JavaWEB
方法名 | 说明 |
---|---|
public boolean delete() | 删除由此抽象路径名表示的文件或目录 |
绝对路径和相对路径的区别
删除目录时的注意事项:
public class FileDemo4 {
public static void main(String[] args) throws IOException {
File f1 = new File("java.txt");
System.out.println(f1.createNewFile());
System.out.println(f1.delete());
File f2 = new File("myfile");
System.out.println(f2.mkdir());
System.out.println(f2.delete());
System.out.println("------------------------");
File f3 = new File("myfile");
System.out.println(f3.mkdir());
File f4 = new File("myfile\\java.txt");
System.out.println(f4.createNewFile());
System.out.println(f4.delete());
System.out.println(f3.delete());
}
}
递归概述:以编程的角度来看,递归指的是方法定义中调用方法本身的现象
递归解决问题的思路:把一个复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解;递归策略只需少量的程序就可以描述出解决过程所需要的多次重复计算
递归解决问题要找到两个内容:
public class DiguiDemo1 {
public static void main(String[] args) {
//一般方法
int[] arr = new int[20];
arr[0] = 1;
arr[1] = 1;
for (int i = 2; i < arr.length; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
System.out.println(arr[19]);
System.out.println(f(20));
}
//递归方法
public static int f(int n) {
if (n==1||n==2){
return 1;
}else {
return f(n - 1) + f(n - 2);
}
}
}
运行结果:
6765
6765
public class DiguiDemo2 {
public static void main(String[] args) {
System.out.println(f(5));
}
public static int f(int n) {
if (n == 1) {
return 1;
} else {
return n * f(n - 1);
}
}
}
运行结果:
120
需求:给定一个路径,请通过递归完成该目录下得所有内容,并把所有文件的绝对路径输出在控制台
public class DiguiDemo3 {
public static void main(String[] args) {
File file1 = new File("F:\\javaworkspace_2022\\md5");
getAllFilePath(file1);
}
public static void getAllFilePath(File srcFile){
File[] fileArray = srcFile.listFiles();
if (fileArray != null){
for (File file : fileArray) {
if (file.isDirectory()){
getAllFilePath(file);
}else {
System.out.println(file.getAbsolutePath());
}
}
}
}
}
IO流概述:
IO流分类:
字节流抽象基类
FileOutputStream:文件输出流用于将数据写入File
使用字节输出流写数据的步骤:
方法名 | 说明 |
---|---|
void write(int b) | 将指定的字节写入此文件输出流一次写一个字节数据 |
void write(byte[] b) | 将b.length字节从指定的字节数组写入此文件输出流一次写一个字节数组数据 |
void write(byte[] b,int off,int len) | 将len字节从指定的字节数组开始,从偏移量off开始写入此文件输出流一次写一个字节数组的部分数据 |
public class FileOutputStreamDemo2 {
public static void main(String[] args) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream("file.txt");
//void write(byte[] b)将b.length字节从指定的字节数组写入此文件输出流一次写一个字节数组数据
//byte[] getBytes();返回字符串对应的字节数组
byte[] bytes = "abcde".getBytes();
// fileOutputStream.write(bytes);
//void write(byte[] b,int off,int len)将len字节从指定的字节数组开始,从偏移量off开始写入此文件输出流一次写一个字节数组的部分数据
fileOutputStream.write(bytes,1,3);
//释放资源
fileOutputStream.close();
}
}
文件内容:bcd
字节流写数据如何现实换行呢?
windows:\r\n
linux:\n
mac:\r
字节流写数据如何实现追加写入呢?
public class FileOutputStreamDemo3 {
public static void main(String[] args) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream("test.txt",true);
for (int i = 0; i < 10; i++) {
fileOutputStream.write("hello".getBytes());
fileOutputStream.write("\r\n".getBytes());
}
}
}
public class FileOutputStreamDemo4 {
public static void main(String[] args) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("Z://file.txt");
fileOutputStream.write("hello".getBytes());
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
需求:把文件file.txt中的内容读取出来并在控制台输出(一次读一个字节数据)
FileInputStream(String name):通过打开与实际文件的连接创建一个FileInputStream,该文件由文件系统中的路径名name命名
使用字节输入流读数据的步骤:
public class FileInputStreamDemo1 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("file.txt");
int read;
while ((read = fileInputStream.read()) != -1) {
System.out.print((char) read);
}
fileInputStream.close();
}
}
复制文本文件(一次读取一个字节流):
public class FileIutputStreamDemo2 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("file.txt");
FileOutputStream fileOutputStream = new FileOutputStream("file2.txt");
int by;
while((by=fileInputStream.read())!=-1){
fileOutputStream.write(by);
}
fileOutputStream.close();
fileInputStream.close();
}
}
复制文本文件(一次读一个字节数组数据)
public class FileInputStreamDemo3 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("fos.txt");
byte[] bytes = new byte[1024];
int len;
while ((len = fileInputStream.read(bytes))!=-1){
System.out.println(new String(bytes,0,len));
}
}
}
复制图片
public class FileInputStreamDemo4 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("1.JPG");
FileOutputStream fileOutputStream = new FileOutputStream("2.JPG");
int len;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes,0,len);
}
fileOutputStream.close();
fileInputStream.close();
}
}
字节缓冲流作用:为了提高读写数据效率
构造方法:
为什么构造方法需要的是字节流,而不是具体的文件或者路径呢?
public class BufferStreamDemo {
public static void main(String[] args) throws IOException {
// BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("bos.txt"));
// bufferedOutputStream.write("hello\r\n".getBytes());
// bufferedOutputStream.write("world\r\n".getBytes());
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("bos.txt"));
// int by;
// while ((by = bufferedInputStream.read())!=-1){
// System.out.print((char) by);
// }
byte[] bytes = new byte[1024];
int len;
while ((len = bufferedInputStream.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, len));
}
bufferedInputStream.close();
}
}
复制视频
public class BufferStreamDemo2 {
public static void main(String[] args) throws IOException {
long startTime = System.currentTimeMillis();
method3();
long endTime = System.currentTimeMillis();
System.out.println("共耗时:" + (endTime - startTime) + "毫秒");
}
public static void method1() throws IOException {
FileInputStream fileInputStream = new FileInputStream("2022zbxcp.mp4");
FileOutputStream fileOutputStream = new FileOutputStream("2022zbxcp2.mp4");
int by;
while ((by = fileInputStream.read()) != -1) {
fileOutputStream.write(by);
}
fileOutputStream.close();
fileInputStream.close();
}
public static void method2() throws IOException {
FileInputStream fileInputStream = new FileInputStream("2022zbxcp.mp4");
FileOutputStream fileOutputStream = new FileOutputStream("2022zbxcp2.mp4");
byte[] bytes = new byte[1024];
int len;
while ((len = fileInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
fileOutputStream.close();
fileInputStream.close();
}
public static void method3() throws IOException {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("2022zbxcp.mp4"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("2022zbxcp2.mp4"));
int by;
while ((by = bufferedInputStream.read()) != -1) {
bufferedOutputStream.write(by);
}
bufferedOutputStream.close();
bufferedInputStream.close();
}
public static void method4() throws IOException {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("2022zbxcp.mp4"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("2022zbxcp2.mp4"));
byte[] bytes = new byte[1024];
int len;
while ((len = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
bufferedOutputStream.close();
bufferedInputStream.close();
}
}
由于字节流操作中文不是特别方便,所以Java就提供了字符流
字符流 = 字节流 + 编码表
汉字在存储的时候,无论选择哪种编码存储,第一个字节都是负数
一个汉字存储:
字符集:
ASCII字符集:
GBXXX字符集:
Unicode字符集:
为表达任意语言的任意字符而设计,是业界的一种标准,也称为统一码、标准万国码。它最多使用4个字节的数字来表达每个字母、符号或者文字。有三种编码方案UTF-8、UTF-16和UTF-32,其中UTF-8最常用。
UTF-8编码:可以用来表示Unicode标准中任意字符,它是电子邮件、网页及其他存储或者传送文字的应用中,优先采用的编码。互联网工程工作小组(IETF)要求所有互联网协议都必须支持UTF-8编码。它使用一至四个字节为每个字符编码。
编码规则:
补充:采用何种规则编码,就要采用对应规则解码,否则就会出现乱码
编码:
编码:
public class StringDemo{
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "中国";
//byte[] getBytes():使用平台的默认字符集将该String编码为一系列字节,将结果存储到新的字节数组中
byte[] bytes = s.getBytes();
System.out.println(Arrays.toString(bytes));
System.out.println("-----------------------");
byte[] bytes2 = s.getBytes("GBK");
System.out.println(Arrays.toString(bytes2));
System.out.println("-----------------------");
String s1 = new String(bytes);
System.out.println(s1);
System.out.println("-----------------------");
String s2 = new String(bytes2,"GBK");
System.out.println(s2);
}
}
字符流抽象基类
字符流中和编码解码问题相关的两个类
public class StringDemo2 {
public static void main(String[] args) throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream("osw.txt"),"UTF-8");
outputStreamWriter.write("中国");
outputStreamWriter.close();
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("osw.txt"),"UTF-8");
int by;
while (((by=inputStreamReader.read()) != -1)){
System.out.print((char)by);
}
inputStreamReader.close();
}
}
方法名 | 说明 |
---|---|
void write(int c) | 写入一个字符 |
void write(char[] cbuf) | 写入一个字符数组 |
void write(char[] cbuf,int off,int len) | 写入字符数组的一部分 |
void write(String str) | 写一个字符串 |
void write(String str,int off,int len) | 写一个字符串的一部分 |
方法名 | 说明 |
---|---|
flush() | 刷新流,还能继续写数据 |
close() | 关闭流,释放资源,但是在关闭之前会刷新流。一旦关闭,就不能再写数据 |
public class OutputStreamWriteDemo {
public static void main(String[] args) throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream("osw.txt"),"UTF-8");
// outputStreamWriter.write(97);
// outputStreamWriter.flush();
// char[] chars = new char[]{'a','b','c','d','e'};
// outputStreamWriter.write(chars);
// outputStreamWriter.write(chars,1,3);
// outputStreamWriter.write("abc");
outputStreamWriter.write("abc",0,2);
outputStreamWriter.close();
}
}
方法名 | 说明 |
---|---|
int read() | 一次读一个字节数据 |
int read(char[] cbuf) | 一次读一个字符数组数据 |
public class IutputStreamReaderDemo {
public static void main(String[] args) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("osw.txt"));
int len;
char[] chars = new char[1024];
while ((len = inputStreamReader.read(chars)) != -1) {
System.out.print(new String(chars,0,len));
}
inputStreamReader.close();
}
}
改进:
public class copyJavaFileDemo2 {
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("MD5.java");
FileWriter fileWriter = new FileWriter("MD52.java");
int len;
char[] chars = new char[1024];
while ((len = fileReader.read(chars)) != -1) {
fileWriter.write(chars, 0, len);
}
fileWriter.close();
fileReader.close();
}
}
构造方法:
public class BufferedStreamDemo {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("bos.txt"));
char[] chars = new char[1024];
int len;
while ((len = bufferedReader.read(chars)) != -1) {
System.out.println(new String(chars,0,len));
}
}
}
用字符缓冲流实现复制java文件:
public class copyJavaFileDemo3 {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("MD5.java"));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("MD52.java"));
char[] chars = new char[1024];
int len;
while ((len = bufferedReader.read(chars))!=-1){
bufferedWriter.write(chars,0,len);
}
bufferedWriter.close();
bufferedReader.close();
}
}
BufferedWriter:
BufferedReader:
public class BufferedStreamDemo2 {
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("stream.txt"));
for (int i = 0; i < 10; i++) {
bufferedWriter.write("hello" + i);
bufferedWriter.newLine();
bufferedWriter.flush();
}
bufferedWriter.close();
BufferedReader bufferedReader = new BufferedReader(new FileReader("stream.txt"));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
}
再改进java复制文件:
public class copyJavaFileDemo4 {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("MD5.java"));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("MD52.java"));
String line;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
bufferedWriter.flush();
}
bufferedWriter.close();
bufferedReader.close();
}
}
集合到文件:
public class ArrayListToTxtDemo {
public static void main(String[] args) throws IOException {
ArrayList<String> arrayList = new ArrayList<String>();
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("array.txt"));
arrayList.add("hello");
arrayList.add("world");
arrayList.add("java");
for (String s : arrayList) {
bufferedWriter.write(s);
bufferedWriter.newLine();
bufferedWriter.flush();
}
bufferedWriter.close();
}
}
文件到集合:
需求:把文本文件中的数据读取到集合中,并遍历集合。
要求:文件中每一行数据是一个集合元素。
public class TxtToArrayListDemo {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("array.txt"));
ArrayList<String> arrayList = new ArrayList<String>();
String line;
while ((line = bufferedReader.readLine()) != null) {
arrayList.add(line);
}
for (String s1 : arrayList) {
System.out.println(s1);
}
}
}
集合到文件(改进版):
public class ArrayListToFileDemo {
public static void main(String[] args) throws IOException {
long startTime = System.currentTimeMillis();
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("student.txt"));
ArrayList<Student> arrayList = new ArrayList<Student>();
Student s1 = new Student("id001", "zhangsan", 22, "北京");
Student s2 = new Student("id002", "lisi", 23, "新疆");
Student s3 = new Student("id003", "wangwu", 24, "广州");
Student s4 = new Student("id004", "zhaoliu", 25, "河北");
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
arrayList.add(s4);
for (Student s : arrayList) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(s.getSid()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress());
bufferedWriter.write(stringBuilder.toString());
bufferedWriter.newLine();
bufferedWriter.flush();
}
bufferedWriter.close();
long endTime = System.currentTimeMillis();
System.out.println("共耗时" + (endTime - startTime) + "毫秒");
}
}
文件到集合(改进版):
public class FileToArrayListDemo {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("student.txt"));
ArrayList<Student> arrayList = new ArrayList<Student>();
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] array = line.split(",");
Student s = new Student();
s.setSid(array[0]);
s.setName(array[1]);
s.setAge(Integer.parseInt(array[2]));
s.setAddress(array[3]);
arrayList.add(s);
}
bufferedReader.close();
for (Student s : arrayList) {
System.out.println(s.getSid() + "," + s.getName() + "," + s.getAge() + "," + s.getAddress());
}
}
}
集合到文件(数据排序改进版)
需求:键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩)
要求:按照学生总分从高到低写入文本文件格式(姓名,语文成绩,数学成绩,英语成绩)
public class TreeSetToFileDemo {
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("score.txt"));
TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int sum = s2.getSum() - s1.getSum();
int num1 = sum == 0 ? s2.getChinese() - s1.getChinese() : sum;
int num2 = num1 == 0 ? s2.getMath() - s1.getMath() : num1;
int name = num2 == 0 ? s1.getName().compareTo(s2.getName()) : num2;
return name;
}
});
for (int i = 0; i < 5; i++) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第" + (i + 1) + "名学生信息:");
System.out.println("姓名:");
String name = scanner.nextLine();
System.out.println("语文成绩:");
int chinese = scanner.nextInt();
System.out.println("数学成绩:");
int math = scanner.nextInt();
System.out.println("英语成绩:");
int english = scanner.nextInt();
Student student = new Student();
student.setName(name);
student.setChinese(chinese);
student.setMath(math);
student.setEnglish(english);
treeSet.add(student);
}
for (Student s : treeSet) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(s.getName()).append(",").append(s.getChinese()).append(",").append(s.getMath()).append(",").append(s.getEnglish());
bufferedWriter.write(stringBuilder.toString());
bufferedWriter.newLine();
bufferedWriter.flush();
}
bufferedWriter.close();
}
}
点名器:
需求:有一个文件里面存储了班级同学的姓名,每一个姓名占一行,要求通过程序实现随机点名器。
public class CallNameDemo {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("name.txt"));
ArrayList<String> arrayList = new ArrayList<String>();
Random random = new Random();
String line;
while ((line = bufferedReader.readLine()) != null) {
arrayList.add(line);
}
bufferedReader.close();
int i = random.nextInt(arrayList.size());
String name = arrayList.get(i);
System.out.println("随机点名的名字为:" + name);
}
}
复制单级文件夹:
public class copyFolderDemo {
public static void main(String[] args) throws IOException {
File srcFolder = new File("F:\\file");
String srcFolderName = srcFolder.getName();
File destFolder = new File("F:\\javaworkspace_2022\\io", srcFolderName);
if (!destFolder.exists()) {
destFolder.mkdir();
}
File[] listFiles = srcFolder.listFiles();
for (File srcFile : listFiles) {
String srcFileName = srcFile.getName();
File destFile = new File(destFolder, srcFileName);
copyFile(srcFile, destFile);
}
}
private static void copyFile(File srcFile, File destFile) throws IOException {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFile));
byte[] bytes = new byte[1024];
int len;
while ((len = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
bufferedOutputStream.close();
bufferedInputStream.close();
}
}
复制多级文件夹:
public class copyFoldersDemo {
public static void main(String[] args) throws IOException {
File srcFile = new File("F:\\file");
File destFile = new File("F:\\javaworkspace_2022\\io");
copyFolder(srcFile, destFile);
}
private static void copyFolder(File srcFile, File destFile) throws IOException {
if (srcFile.isDirectory()) {
String srcFileName = srcFile.getName();
File newFolder = new File(destFile, srcFileName);
if (!newFolder.exists()) {
newFolder.mkdir();
}
File[] filesArray = srcFile.listFiles();
for (File file : filesArray) {
copyFolder(file, newFolder);
}
} else {
//文件
File newFile = new File(destFile, srcFile.getName());
copyFile(srcFile, newFile);
}
}
private static void copyFile(File srcFile, File destFile) throws IOException {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFile));
byte[] bytes = new byte[1024];
int len;
while ((len = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
bufferedOutputStream.close();
bufferedInputStream.close();
}
}
public class CopyFileExceptionDemo {
public static void main(String[] args) {
method();
}
public static void method() {
try (FileReader fileReader = new FileReader("file.txt");
FileWriter fileWriter = new FileWriter("file2.txt");) {
int len;
char[] chars = new char[1024];
while ((len = fileReader.read(chars)) != -1) {
fileWriter.write(chars, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
自己实现键盘录入数据:
输出语句的本质:是一个标准的输出流
public class SystemInDemo {
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入一个字符串:");
String line = bufferedReader.readLine();
System.out.println("输入的字符是:" + line);
}
}
打印流分类:
打印流的特点:
字节打印流
public class SystemOutDemo {
public static void main(String[] args) throws IOException {
PrintStream printStream = new PrintStream("ps.txt");
// printStream.write(97);
//写多少就是多少
printStream.println(97);
printStream.println(98);
printStream.close();
}
}
字符打印流PrintWriter的构造方法:
方法名 | 说明 |
---|---|
PrintWriter(String fileName) | 使用指定的文件名创建一个新的PrintWriter,而不需要自动执行刷新 |
PrintWriter(Writer out,boolean autoFlush) | 创建一个新的PrintWriter,out:字符输出流;autoFlush:一个布尔值,如果为真,则println,printf或format方法刷新输出缓冲区 |
public class PrintWriterDemo {
public static void main(String[] args) throws IOException {
PrintWriter printWriter = new PrintWriter(new FileWriter("pw.txt",true));
printWriter.write("hello");
printWriter.write("world");
printWriter.close();
}
}
复制Java文件:
public class CopyJavaDemo {
public static void main(String[] args) throws IOException {
// BufferedReader bufferedReader = new BufferedReader(new FileReader("MD5.java"));
// BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("MD52.java"));
// String line;
// while ((line = bufferedReader.readLine())!=null){
// bufferedWriter.write(line);
// bufferedWriter.newLine();
// bufferedWriter.flush();
// }
// bufferedWriter.close();
// bufferedReader.close();
BufferedReader bufferedReader = new BufferedReader(new FileReader("MD5.java"));
PrintWriter printWriter = new PrintWriter(new FileWriter("MD52.java"),true);
String line;
while ((line = bufferedReader.readLine())!=null){
printWriter.println(line);
}
printWriter.close();
bufferedReader.close();
}
}
对象序列化:就是将对象保存到磁盘中,或者在网络中传输对象
这种机制就是使用一个字节序列表示一个对象,该字节序列包含:对象的类型、对象的数据和对象中存储的属性等信息
字节序列写道文件之后,相当于文件中持久保存了一个对象的信息
反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反序列化
要实现序列化和反序列化就要使用对象序列化流和对象反序列化流:
将Java对象的原始数据类型和图形写入OutputStream,可以使用ObjectInputStream读取(重构)对象,可以通过使用流的文件来实现对象的持久存储。如果流是网络套接字流,则可以在另一个主机上或者另一个进程中重构对象
构造方法:
序列化对象的方法:
注意:
序列化: ObjectOutputStream
public class ObjectOutputStreamDemo {
public static void main(String[] args) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("ddd.txt"));
Student student = new Student("xuanxuan",22);
objectOutputStream.writeObject(student);
objectOutputStream.close();
}
}
public class Student implements Serializable {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
反序列化:ObjectInputStream
构造方法:
反序列化对象的方法:
public class ObjectInputStreamDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("ddd.txt"));
Object obj = objectInputStream.readObject();
Student s = (Student) obj;
System.out.println(s.getName()+","+s.getAge());
objectInputStream.close();
}
}
常见问题:
用对象序列化流序列化了一个对象后,假如我们修改了对象所属的类文件,读取数据会不会出问题呢?
如果出了问题,如何解决呢?
private static final long serialVersionUID = 42L;
如果一个对象中的某个成员变量的值不想被序列化,又该如何实现呢?
private transient String name;
概述:
public class PropertiesDemo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("id001", "xuanxuan1");
properties.put("id002", "xuanxuan2");
properties.put("id003", "xuanxuan3");
Set<Object> keySet = properties.keySet();
for (Object key : keySet) {
Object value = properties.get(key);
System.out.println(key + "," + value);
}
}
}
特有方法:
方法名 | 说明 |
---|---|
Object setProperty(String key,String value) | 设置集合的键和值,都是String类型,底层调用Hashtable方法put |
String getProperty(String key) | 使用此属性列表中指定的键搜索属性 |
Set stringPropertyNames() | 从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串 |
public class PropertiesDemo2 {
public static void main(String[] args) {
Properties properties = new Properties();
//Object setProperty(String key,String value)设置集合的键和值,都是String类型,底层调用Hashtable方法put
properties.setProperty("id001", "xuanxuan1");
properties.setProperty("id002", "xuanxuan2");
properties.setProperty("id003", "xuanxuan3");
//String getProperty(String key)使用此属性列表中指定的键搜索属性\
System.out.println(properties.getProperty("id001"));
System.out.println(properties.getProperty("id002"));
System.out.println(properties.getProperty("id003"));
//Set stringPropertyNames()从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串
Set<String> id = properties.stringPropertyNames();
for (String key : id) {
String value = properties.getProperty(key);
System.out.println(key + "," + value);
}
System.out.println(properties);
}
}
运行结果:
xuanxuan1
xuanxuan2
xuanxuan3
id003,xuanxuan3
id002,xuanxuan2
id001,xuanxuan1
{id003=xuanxuan3, id002=xuanxuan2, id001=xuanxuan1}
Properties和IO流结合的方法:
方法名 | 说明 |
---|---|
void load(InputStream inStream) | 从输入字节流读取属性列表(键和元素对) |
void load(Reader reader) | 从输入字符流读取属性列表(键和元素对) |
void store(OutputStream out,String comments) | 将此属性列表(键和元素对)写入此Properties表中,以适合用于使用load(InputStream)方法的格式写入输出字节流 |
void store(Writer writer,String comments) | 将此属性列表(键和元素对)写入此Properties表中,以适合使用load(Reader)方法的格式写入输出字符流 |
public class PropertiesDemo3 {
public static void main(String[] args) throws IOException {
// myStore();
myLoad();
}
private static void myLoad() throws IOException {
Properties properties = new Properties();
FileReader fileReader = new FileReader("fw.txt");
properties.load(fileReader);
fileReader.close();
System.out.println(properties);
}
private static void myStore() throws IOException {
Properties properties = new Properties();
properties.setProperty("id001","xuanxuan1");
properties.setProperty("id002","xuanxuan2");
properties.setProperty("id003","xuanxuan3");
FileWriter fileWriter = new FileWriter("fw.txt");
properties.store(fileWriter,null);
fileWriter.close();
}
}
运行结果:
{id003=xuanxuan3, id002=xuanxuan2, id001=xuanxuan1}
案例:游戏次数
需求:请写程序实现猜数字小游戏只能试玩3次,如果还想玩提示:“次数不足,游戏结束!”
public class GuessNumber {
private GuessNumber() {
}
public static void start() {
Random random = new Random();
int number = random.nextInt(100) + 1;
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入你要猜的数字:");
int guessNumber = scanner.nextInt();
if (guessNumber > number) {
System.out.println("你猜的数字" + guessNumber + "大了");
} else if (guessNumber < number) {
System.out.println("你猜的数字" + guessNumber + "小了");
} else {
System.out.println("猜中了");
break;
}
}
}
}
public class PropertiesDemo4 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
FileReader fileReader = new FileReader("number.txt");
properties.load(fileReader);
fileReader.close();
String count = properties.getProperty("count");
int number = Integer.parseInt(count);
if (number >= 3) {
System.out.println("次数不足,游戏结束!");
} else {
GuessNumber.start();
number++;
properties.setProperty("count", String.valueOf(number));
FileWriter fileWriter = new FileWriter("number.txt");
properties.store(fileWriter,null);
fileWriter.close();
}
}
}
count=0
没有什么使我停留——除了目的,纵然岸旁有玫瑰、有绿荫、有宁静的港湾,我是不系之舟。