黑马全套Java教程(一)
黑马全套Java教程(二)
黑马全套Java教程(三)
黑马全套Java教程(四)
黑马全套Java教程(五)
黑马全套Java教程(六)
黑马全套Java教程(七)
本博客从黑马教学视频d272开始,博客只做代码记录,方便后续快速复习,视频链接
32 File
32.1 概述
File:它是文件和目录路径名的抽象表示
- 文件和目录是可以通过File封装成对象的
- 对于File而言,其封装的并不是一个真正存在的文件,仅仅是一个路径名而已。它可以是存在的,也可以是不存在的。将来是要通过具体的操作把这个路径的内容转换为具体存在的。
方法名 | 说明 |
---|---|
File(String pathname) | 通过将给定的路径名字符串转换为抽象路径名来创建新的File实例 |
File(String parent, String child) | 从父路径名字符串和子路径名字符串创建新的File实例 |
File(File parent, String child) | 从父抽象路径名和子路径名字符串创建新的File实例 |
import java.io.File;
//三个构造方法的使用
public class Demo01 {
public static void main(String[] args) {
//1
File f1 = new File("C:\\Users\\14051\\Desktop\\java_learning\\HelloWorld.java"); //抽象路径表示形式,并不是说这个路径存在
System.out.println(f1);
//2
File f2 = new File("E:\\itcast", "java.txt");
System.out.println(f2);
//3
File f3 = new File("E:\\itcast");
File f4 = new File(f3, "java.txt");
System.out.println(f4);
}
}
32.2 创建文件\文件夹方法
import java.io.File;
import java.io.IOException;
public class Demo02 {
public static void main(String[] args) throws IOException {
//需求1:D盘itcast文件夹下创建文件java.txt
File f1 = new File("D:\\itcast\\java.txt");
System.out.println(f1.createNewFile()); //不存在就创建并返回true;存在就不创建,返回false
//需求2:在itcast文件夹下创建目录
File f2 = new File("D:\\itcast\\JavaSE");
System.out.println(f2.mkdir());
//需求3:创建嵌套子目录
File f3 = new File("D:\\itcast\\JavaEE\\JavaWeb");
System.out.println(f3.mkdirs());
//总结:createNewFile()创建文件,mkdir,mkdirs创建目录
}
}
32.3 常见方法
import java.io.File;
//8个常见方法的使用
public class Demo4 {
public static void main(String[] args) {
File f = new File("C:\\programming_software\\JetBrains\\IdeaProjects\\JavaSE_Code\\D34\\src\\myFile\\java.txt");
//1.是否为文件
System.out.println(f.isFile());
//2.是否为目录
System.out.println(f.isDirectory());
//3.是否存在
System.out.println(f.exists());
//4.获取绝对路径
System.out.println(f.getAbsolutePath());
//5.返回路径名字符串
System.out.println(f.getPath());
//6.获取文件或目录名称
System.out.println(f.getName());
System.out.println("---------------------------");
//7.获取文件夹下所有文件的字符串
File f2 = new File("D:\\itcast");
String[] strArray = f2.list();
for (String str : strArray) {
System.out.println(str);
}
System.out.println("-----------------------------");
File[] fileArray = f2.listFiles(); //获取绝对路径
for (File file : fileArray) {
System.out.println(file);
}
System.out.println("------------------------------");
for (File file : fileArray) {
// System.out.println(file.getName());
if(file.isFile()){
System.out.println(file.getName());
}
}
System.out.println("-------------------------------");
}
}
32.4 删除方法
import java.io.File;
import java.io.IOException;
//删除功能
public class Demo05 {
public static void main(String[] args) throws IOException {
File f1 = new File("java1.txt"); //创建在项目文件下
System.out.println(f1.createNewFile());
//删除
System.out.println(f1.delete());
//创建和删除目录
File f2 = new File("itcast");
System.out.println(f2.mkdir());
System.out.println(f2.delete());
System.out.println("----------------------");
//创建cast目录,接着在目录下创建java.txt文件
File f3 = new File("cast");
System.out.println(f3.mkdir());
File f4 = new File("cast\\java.txt");
System.out.println(f4.createNewFile());
System.out.println("----------------------------");
//再次删除:注意得先删除路径下的内容,才能删除文件夹
System.out.println(f3.delete());
System.out.println(f4.delete());
System.out.println(f3.delete());
}
}
32.5 递归
//不死神兔递归
public class Demo01 {
public static void main(String[] args) {
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);
}
}
}
案例一:递归求阶乘
public class Demo02 {
public static void main(String[] args) {
System.out.println(jiecheng(5));
}
public static int jiecheng(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * jiecheng(n - 1);
}
}
}
案例二:遍历目录
package myDIGui;
import java.io.File;
//案例:递归目录,只获取文件的绝对路径
public class Demo03 {
public static void main(String[] args) {
File f1 = new File("D:\\itcast");
getAllFilePath(f1);
}
public static void getAllFilePath(File srcFile) {
//获取所有问价或目录的file数组
File[] fileArray = srcFile.listFiles();
if (fileArray != null) { //判断该目录下是否有内容
for (File file : fileArray) {
//判断该文件是否为目录
if (file.isDirectory()) {
getAllFilePath(file);
} else {
System.out.println(file.getAbsolutePath());
}
}
}
}
}
33 字节流
33.1 IO流概述
IO流分类:
1、按照数据的流向:
输入流:读数据
输出流:写数据
2、按照数据类型:
字节流:字节输入流、字节输出流
字符流:字符输入流、字符输出流
33.2 字节流写数据:FileOutputStream
字节流抽象基类
- InputStream:表示字节输入流的所有类的超类
- OutputStream:表示字节输出流的所有类的超类
- 子类名特点:都是以其父类名作为子类名的后缀
FileOutputStream:用于将数据写入File
- FileOutputStream(String name):创建文件输出流以指定的文成写入文件
使用字节输出流写数据的步骤:
1、创建字节输出流对象(调用系统功能创建文件,创建字节输出流对象,让字节输出流对象指向文件)
2、调用字节输出流对象的写数据方法
3、close释放资源
l例:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//将数据写入文件
public class Demo01 {
public static void main(String[] args) throws IOException {
//1. 创建字节输出流对象:FileOutputStream
FileOutputStream fos = new FileOutputStream("fos.txt");
//2. 写数据
fos.write(97); //记事本显示a
fos.write(57); //字符9
fos.write(55); //字符7
//3. 释放资源 关闭此输出流,并释放与此流相关联的任何系统资源
fos.close();
}
}
33.3 字节流写数据的3种方式
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
//write三个构造方法的使用
public class Demo02 {
public static void main(String[] args) throws IOException {
// FileOutputStream fos = new FileOutputStream("fos.txt");
FileOutputStream fos = new FileOutputStream("fos.txt", true); //true实现追加写入
//1. 一次写入一个
fos.write(97);
//2. 用字节数组,一次性写入多个字节
byte[] bys = {98, 99, 100, 101};
fos.write(bys);
byte[] bys2 = "fghij".getBytes();
fos.write(bys2);
byte[] bys3 = "张曼玉".getBytes();
fos.write(bys3);
//3. 写入部分字节
byte[] bys4 = "abcde".getBytes();
fos.write(bys4, 1, 3); //索引为1开始写三个,即bcd
fos.close();
}
}
33.4 字节流写数据的两个小问题
一是怎么换行?
二是怎么追加数据?
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
//字节流写数据的两个小问题
public class Demo3 {
public static void main(String[] args) throws IOException {
//创建字节输出流对象
FileOutputStream fos = new FileOutputStream("fos.txt");
// FileOutputStream fos = new FileOutputStream("fos.txt", true); //true实现追加写入
//写数据
for (int i = 0; i < 10; i++) {
fos.write("hello".getBytes());
//2. 实现换行
fos.write("\r\n".getBytes());
}
fos.close();
}
}
33.5 字节流写数据加异常处理
这个其实就是用try–catch实现,而不用throws抛出异常了。步骤更繁琐,其实没必要
package myByteStream;
import java.io.FileOutputStream;
import java.io.IOException;
//字节流写数据加入异常处理
public class Demo04 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("fos.txt");
fos.write("hello".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
33.6 字节流读数据:FileInputStream
1. 一次读一个字节数据
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//读数据 FileInputStream
public class Demo05 {
public static void main(String[] args) throws IOException {
FileInputStream fi = new FileInputStream("fos.txt");
//第一次读取数据
// int a = fi.read();
// System.out.println(a); //h对应104
// System.out.println((char) a); //h
//
// //第二次
// System.out.println((char) fi.read()); //没有数据的话会返回-1
// int by = fi.read();
// while(by != -1){
// System.out.print((char)by);
// by = fi.read();
// }
//优化上面代码
int by;
while ((by = fi.read()) != -1) {
System.out.print((char) by);
}
fi.close();
}
}
案例:复制文本文件
package myByteStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//案例:复制文本文件,把文件a的内容读取复制,生成文件b中存储
public class Demo06 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("fos.txt");
FileOutputStream fos = new FileOutputStream("new_fos.txt");
//读取,写入
int by;
while((by=fis.read())!=-1){
fos.write(by);
}
//释放资源
fis.close();
fos.close();
}
}
2. 一次读一个字节数组数据
package myByteStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Demo07 {
public static void main(String[] args) throws IOException {
//创建字节输入流对象
FileInputStream fis = new FileInputStream("fos.txt");
byte[] bys = new byte[1024];
int len;
while ((len = fis.read(bys)) != -1) {
System.out.println(new String(bys, 0, len));
}
//释放资源
fis.close();
}
}
案例:复制图片
package myByteStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//复制图片
public class Demo8 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\itcast\\mn.jpg");
FileOutputStream fos = new FileOutputStream("new_mn.jpg");
byte[] bys = new byte[1024];
int len;
while ((len = fis.read(bys)) != -1) {
fos.write(bys, 0, len);
}
fis.close();
fos.close();
}
}
33.7 字节缓冲流:BufferOutputStream
import java.io.*;
public class Demo01 {
public static void main(String[] args) throws IOException {
// FileOutputStream fos = new FileOutputStream("fos.txt");
// BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));
bos.write("hello\r\n".getBytes());
bos.write("world\r\n".getBytes());
//释放资源
bos.close();
//读数据
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bos.txt"));
// int by;
// while ((by = bis.read()) != -1) {
// System.out.print((char) by);
// }
//读数据第二种方式:一次读取一个数组的数据
byte[] bys = new byte[1024];
int len;
while ((len = bis.read(bys)) != -1) {
System.out.println(new String(bys, 0, len));
}
bis.close();
}
}
案例:复制视频
package myByteStream.Demo2;
import java.io.*;
//复制视频
public class Demo02 {
public static void main(String[] args) throws IOException {
//记录开始时间
long startTime = System.currentTimeMillis();
//复制视频
// method1();
// method2();
// method3();
method4();
//记录结束时间
long endTime = System.currentTimeMillis();
System.out.println("共耗时:" + (endTime - startTime) + "毫秒");
}
//1.基本字节流一次读写一个字节
public static void method1() throws IOException { //共耗时:15031毫秒
FileInputStream fis = new FileInputStream("D:\\itcast\\视频.mp4");
FileOutputStream fos = new FileOutputStream("D:\\itcast\\new_视频.mp4");
int by;
while ((by = fis.read()) != -1) {
fos.write(by);
}
fos.close();
fis.close();
}
//2.基本字节流一次读写一个字节数组
public static void method2() throws IOException { //共耗时:25毫秒
FileInputStream fis = new FileInputStream("D:\\itcast\\视频.mp4");
FileOutputStream fos = new FileOutputStream("D:\\itcast\\new_视频.mp4");
byte[] bys = new byte[1024];
int len;
while ((len = fis.read(bys)) != -1) {
fos.write(bys, 0, len);
}
fos.close();
fis.close();
}
//3.字节缓冲流一次读写一个字节
public static void method3() throws IOException { //共耗时:77毫秒
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\itcast\\视频.mp4"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\itcast\\new_视频.mp4"));
int by;
while ((by = bis.read()) != -1) {
bos.write(by);
}
bis.close();
bos.close();
}
//4.字节缓冲流一次读写一个字节数组
public static void method4() throws IOException { //共耗时:7毫秒
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\itcast\\视频.mp4"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\itcast\\new_视频.mp4"));
byte[] bys = new byte[1024];
int len;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}
34 字符流
由于字节流操作中文不是特别的方便,所以Java就提供了字符流
字符流 = 字节流 + 编码表
例:字符串中的编码解码问题
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class Demo02 {
public static void main(String[] args) throws UnsupportedEncodingException {
//定义一个字符串
String s = "中国";
byte[] bys = s.getBytes("GBK"); //编码
System.out.println(Arrays.toString(bys));
String ss = new String(bys, "GBK"); //解码
System.out.println(ss);
}
}
例:字符流中的编码解码问题
import java.io.*;
//字节流读取数据
public class Demo01 {
public static void main(String[] args) throws IOException {
// FileOutputStream fos = new FileOutputStream("osw.txt");
// OutputStreamWriter osw = new OutputStreamWriter(fos);
// OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"));
// OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"), "UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"), "GBK");
osw.write("中国");
osw.close();
//读数据
InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt"),"GBK");
//一次读取一个字符数据
int ch;
while((ch=isr.read())!=-1){
System.out.print((char) ch);
}
isr.close();
}
}
34.1 写数据的5种方式:OutputStreamWriter
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
//write方法演示
public class Demo02 {
public static void main(String[] args) throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"));
// osw.write(97);
// //void slush() 刷新流
// osw.flush();
// osw.write(98);
osw.flush();
// osw.write(99);
// osw.close(); //自带刷新, 后面接着写数据会报错
//写入字符数组数据
// char[] chs = {'a', 'b', 'c', 'd', 'e'};
// osw.write(chs);
//写入部分数组数据
// osw.write(chs, 1, 3);
//一次写入一个字符串
// osw.write("abcdefg");
//写入字符串的部分
osw.write("anceghj", 1, 3);
osw.close();
}
}
34.2 读数据的两种方式:InputStreamReader
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
//读数据
public class Demo03 {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt"));
// //1. 一次读一个字符数据
// int ch;
// while ((ch = isr.read()) != -1) {
// System.out.print((char) ch);
// }
//2. 一次读一个字符数组数据
char[] chs = new char[1024];
int len;
while ((len = isr.read(chs)) != -1) {
System.out.print(new String(chs, 0, len));
}
isr.close();
}
}
案例:复制java文件
package myCharStream.Demo2;
import java.io.*;
import java.util.Objects;
public class Demo04 {
public static void main(String[] args) throws IOException {
//读对象
InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\itcast\\demo01.java"));
//写对象
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:\\itcast\\new_demo01.java"));
//两种方式
// //1.一次读写一个字符数据
// int ch;
// while ((ch = isr.read()) != -1) {
// osw.write(ch);
// }
//2.一次读写一个字符数组数据
char[] chs = new char[1024];
int len;
while ((len = isr.read(chs)) != -1) {
osw.write(chs, 0, len);
}
osw.close();
isr.close();
}
}
案例二:案例一改进版
package myCharStream.Demo03;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Demo01 {
public static void main(String[] args) throws IOException {
//根据数据源创建字符输入流对象
FileReader fr = new FileReader("D:\\itcast\\demo01.java");
FileWriter fw = new FileWriter("D:\\itcast\\new_demo.java");
// //读写数据
// int ch;
// while((ch= fr.read())!=-1){
// fw.write(ch);
// }
char[] chs = new char[1024];
int len;
while ((len = fr.read(chs)) != -1) {
fw.write(chs, 0, len);
}
//释放资源
fw.close();
fr.close();
}
}
34.3 字符缓冲流:BufferedWriter
import java.io.*;
public class Demo02 {
public static void main(String[] args) throws IOException {
// FileWriter fw = new FileWriter("nw.txt");
// BufferedWriter bw = new BufferedWriter(fw);
BufferedWriter bw = new BufferedWriter(new FileWriter("nw.txt"));
bw.write("abcedf");
bw.close();
BufferedReader br = new BufferedReader(new FileReader("nw.txt"));
int ch;
while((ch=br.read())!=-1){
System.out.print((char) ch);
}
// char[] chs = new char[1024];
// int len;
// while ((len = br.read(chs)) != -1) {
// System.out.print(new String(chs, 0, len));
// }
}
}
案例
package myCharStream.Demo03;
import java.io.*;
public class Demo03 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("nw.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("new_nw.txt"));
int ch;
while ((ch = br.read()) != -1) {
bw.write(ch);
}
// char[] chs = new char[1024];
// int len;
// while ((len = br.read(chs)) != -1) {
// bw.write(chs, 0, len);
// }
br.close();
bw.close();
}
}
34.4 字符缓冲流特有功能
package myCharStream.Demo04;
import java.io.*;
public class Demo01 {
public static void main(String[] args) throws IOException {
// BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
// //写数据
// for (int i = 0; i < 10; i++) {
// bw.write("hello" + i);
bw.write("\r\n");
// bw.newLine(); //写一行,换一行,刷一行
// bw.flush();
// }
//
// //释放资源
// bw.close();
//创建字符缓冲流入流
BufferedReader br = new BufferedReader(new FileReader("bw.txt"));
// String line = br.readLine();
// System.out.println(line);
// //再读一行
// line = br.readLine();
// System.out.println(line);
//循环改进
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
案例:
package myCharStream.Demo04;
import java.io.*;
public class Demo02 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("D:\\itcast\\Demo01.java"));
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\itcast\\new_demo.java"));
//读写数据,复制文件
String line;
while((line=br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush(); //写一行,换一行,刷一行
}
br.close();
bw.close();
}
}
34.5 IO流小结
案例:集合到文件
package myCharStream.Demo05;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
//案例:集合数据写入文件
public class Demo01 {
public static void main(String[] args) throws IOException {
//创建ArrayList集合
ArrayList<String> array = new ArrayList<>();
//集合中添加字符串
array.add("hello");
array.add("world");
array.add("java");
//创建字符缓冲输出流对象
BufferedWriter bw = new BufferedWriter(new FileWriter("array.txt"));
//遍历集合,到文件
for (String s : array) {
bw.write(s);
bw.newLine();
bw.flush();
}
//释放资源
bw.close();
}
}
案例:文件到集合
package myCharStream.Demo05;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
//案例文本文件中数据写入集合
public class Demo02 {
public static void main(String[] args) throws IOException {
//创建字符缓冲输入流对象
BufferedReader br = new BufferedReader(new FileReader("array.txt"));
//创建ArrayList集合对象
ArrayList<String> array = new ArrayList<>();
//读数据
String line;
while ((line = br.readLine()) != null) {
array.add(line);
}
//释放资源
br.close();
//遍历集合,查看数据
for (String s : array) {
System.out.println(s);
}
}
}
案例:点名器
package myCharStream.Demo05;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
public class Demo03 {
public static void main(String[] args) throws IOException {
//创建字符缓冲输入流对象
BufferedReader br = new BufferedReader(new FileReader("D:itcast\\names.txt"));
//创建ArrayList集合对象
ArrayList<String> array = new ArrayList<>();
String line;
while((line=br.readLine())!=null){
array.add(line);
}
//释放资源
br.close();
//使用random产生随机数
Random r = new Random();
int index = r.nextInt(array.size());
//把产生的随机数作为索引取值
String name = array.get(index);
//输出
System.out.println(name);
}
}
案例:文件到集合改进版
package myCharStream.Demo06;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class Demo01 {
public static void main(String[] args) throws IOException {
//创建集合
ArrayList<Student> array = new ArrayList<>();
//创建学生对象
Student s1 = new Student("01", "林青霞", 30, "西安");
Student s2 = new Student("02", "张曼玉", 35, "武汉");
Student s3 = new Student("03", "王祖贤", 33, "郑州");
//把学生对象添加到集合中
array.add(s1);
array.add(s2);
array.add(s3);
//创建字符缓冲输出流对象
BufferedWriter bw = new BufferedWriter(new FileWriter("student.txt"));
//遍历集合,得到每个学生对象
for (Student s : array) {
//拼接学生
StringBuilder sb = new StringBuilder();
sb.append(s.getSid()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress());
//写数据
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
//释放资源
bw.close();
}
}
案例:文件到集合改进版
package myCharStream.Demo06;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Demo02 {
public static void main(String[] args) throws IOException {
//创建字符缓冲输入流对象
BufferedReader br = new BufferedReader(new FileReader("D:\\itcast\\student.txt"));
//创建ArrayList集合对象
ArrayList<Student> array = new ArrayList<>();
//调用字符缓冲输入流对象的方法读数据
String line;
while((line=br.readLine())!=null){
//读取的数据写入数组
String[] strArray = line.split(",");
//创建学生对象
Student s = new Student();
//给学生赋值
s.setSid(strArray[0]);
s.setName(strArray[1]);
s.setAge(Integer.parseInt(strArray[2]));
s.setAddress(strArray[3]);
//学生对象添加到集合
array.add(s);
}
//释放资源
br.close();
//遍历集合查看数据
for(Student s : array){
System.out.println(s.getSid()+","+s.getName()+","+s.getAge()+","+s.getAddress());
}
}
}
案例:集合到文件
package TestDemo;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
public class Demo01 {
public static void main(String[] args) throws IOException {
//创建TreeSet集合
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//成绩排序
int num = s2.getSum() - s1.getSum();
//次要条件
int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2;
int num4 = num3 == 0 ? s1.getName().compareTo(s2.getName()) : num3;
return num4;
}
});
//键盘录入学生数据
for (int i = 0; i < 5; i++) {
Scanner sc = new Scanner(System.in);
System.out.println("请录入第" + (i + 1) + "个学生信息:");
System.out.println("姓名:");
String name = sc.nextLine();
System.out.println("语文成绩:");
int chinese = sc.nextInt();
System.out.println("数学成绩:");
int math = sc.nextInt();
System.out.println("英语成绩:");
int english = sc.nextInt();
//创建学生对象,并赋值
Student s = new Student();
s.setName(name);
s.setChinese(chinese);
s.setMath(math);
s.setEnglish(english);
//学生添加到集合
ts.add(s);
}
//创建字符缓冲流对象
BufferedWriter bw = new BufferedWriter(new FileWriter("ts.txt"));
//遍历集合,得到每一个学生对象
for (Student s : ts) {
//拼接数据
StringBuilder sb = new StringBuilder();
sb.append(s.getName()).append(",").append(s.getChinese()).append(",").append(s.getMath()).append(",").append(s.getEnglish()).append(",").append(s.getSum());
//调用字符缓冲输出流对象的方法写数据
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
//释放资源
bw.close();
}
}
案例:复制单级文件夹
package TestDemo;
import java.io.*;
public class Demo02 {
public static void main(String[] args) throws IOException {
//创建数据源目录File对象
File srcFolder = new File("D:\\itcast");
//获取数据源目录File对象的名称
String srcFolderName = srcFolder.getName();
//创建目的地目录File对象
File destFolder = new File("D:\\new_itcast");
//判断目的地目录是否存在,不存在则创建
if(!destFolder.exists()){
destFolder.mkdir();
}
//获取数据源目录下所有文件的File数组
File[] listFiles = srcFolder.listFiles();
//遍历File数组
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 bis = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
byte[] bys = new byte[1024];
int len;
while((len=bis.read())!=-1){
bos.write(bys,0,len);
}
bos.close();
bis.close();
}
}
案例:复制多级文件夹
package TestDemo;
import java.io.*;
public class Demo03 {
public static void main(String[] args) throws IOException {
//创建数据源File对象
File srcFile = new File("D:\\itcast");
//创建目的地File对象
File destFile = new File("D:\\new_itcast");
//判断目的地目录是否存在,不存在则创建
if (!destFile.exists()) {
destFile.mkdir();
}
//复制文件夹
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下所有文件或目录的File数组
File[] fileArray = srcFile.listFiles();
for (File file : fileArray) {
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 bis = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
byte[] bys = new byte[1024];
int len;
while ((len = bis.read()) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}
34.6 复制文件的异常处理
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//复制文件 加入异常处理
public class Demo04 {
public static void main(String[] args) {
}
//抛出处理
public static void method1() throws IOException {
FileReader fr = new FileReader("fr.txt");
FileWriter fw = new FileWriter("fw.txt");
char[] chs = new char[1024];
int len;
while ((len = fr.read()) != -1) {
fw.write(chs, 0, len);
}
fw.close();
fr.close();
}
//try...catch...finally
public static void method2() {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("fr.txt");
fw = new FileWriter("fw.txt");
char[] chs = new char[1024];
int len;
while ((len = fr.read()) != -1) {
fw.write(chs, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//JDK7的改进方案
public static void method3() {
try (FileReader fr = new FileReader("fr.txt");
FileWriter fw = new FileWriter("fw.txt");) {
char[] chs = new char[1024];
int len;
while ((len = fr.read()) != -1) {
fw.write(chs, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} //自动释放资源,不需要close
}
//JDK9改进方案 有啥用???还是要抛出
public static void method4() throws IOException {
FileReader fr = new FileReader("fr.txt");
FileWriter fw = new FileWriter("fw.txt");
try (fr; fw) {
char[] chs = new char[1024];
int len;
while ((len = fr.read()) != -1) {
fw.write(chs, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} //自动释放资源,不需要close
}
}
35 特殊操作流
35.1 标准输入输出流
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
//标准输入流
public class Demo01 {
public static void main(String[] args) throws IOException {
//标准输入流,数据来自键盘输入
// InputStream is = System.in;
//字节读数据
// int by;
// while ((by = is.read()) != -1) {
// System.out.println((char) by);
// }
// //如何把字节流转换为字符流?:转换流
// InputStreamReader isr = new InputStreamReader(is);
// //使用字符流能不能够实现一次读取一行数据?:这是字符缓冲输入流的特有方法
// BufferedReader br = new BufferedReader(isr);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入一个字符串:");
String line = br.readLine();
System.out.println("你输入的字符串是:" + line);
System.out.println("请输入一个整数:");
int i = Integer.parseInt(br.readLine());
System.out.println("你输入的整数是:" + i);
//自己实现键盘录入数据太麻烦了,所以java就提供了一个类供我们使用
Scanner sc = new Scanner(System.in);
}
}
标准输出流:
package myOtherStream;
import java.io.PrintStream;
//标准输出流
public class Demo02 {
public static void main(String[] args) {
//public static final PrintStream out:标准输出流
PrintStream ps = System.out;
//能够方便地打印各种数据值
// ps.print("hello");
// ps.print(100);
// ps.println("world");
// ps.println(200);
//System.out的本质是一个字节输出流
System.out.println("hello");
System.out.println(100);
}
}
35.2 打印流
字节打印流:PrintStream
字符打印流:PrintWriter
打印流特点:只负责输出数据,不负责读取数据
例:字节打印流
import java.io.FileNotFoundException;
import java.io.PrintStream;
//字节打印流
public class Demo03 {
public static void main(String[] args) throws FileNotFoundException {
PrintStream ps = new PrintStream("ps.txt");
//写数据
//字节输出流有的方法
ps.write(97); //a
//使用特有方法写数据
ps.print(97); //97
ps.println(98);
//释放文件
ps.close();
}
}
字符打印流
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
//字符打印流
public class Demo04 {
public static void main(String[] args) throws IOException {
// PrintWriter pw = new PrintWriter("pw.txt");
// pw.write("hello");
// pw.write("\r\n");
// pw.flush();
// pw.write("world");
// pw.flush();
// pw.println("hello");
// pw.flush();
// pw.println("world");
// pw.flush();
PrintWriter pw = new PrintWriter(new FileWriter("pw.txt"), true); //true实现自动刷新
pw.println("hello");
pw.println("world");
pw.close();
}
}
案例:复制java文件
package myOtherStream;
import java.io.*;
//案例:复制文件
public class Demo05 {
public static void main(String[] args) throws IOException {
/* //根据数据源创建字符输入流对象
BufferedReader br = new BufferedReader(new FileReader("D:\\itcast\\Demo01.java"));
//根据目的地创建字符输出流对象
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\itcast\\copy.java"));
//读写数据,复制文件
String line;
while((line=br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
//释放资源
bw.close();
br.close();
*/
BufferedReader br = new BufferedReader(new FileReader("D:\\itcast\\Demo01.java"));
PrintWriter pw = new PrintWriter(new FileWriter("D:\\itcast\\new_copy.java"), true);
//读写数据,复制文件
String line;
while((line=br.readLine())!=null){
pw.println(line);
}
//释放资源
pw.close();
br.close();
}
}
35.3 对象序列化流:ObjectOutputStream
对象序列化:就是把对象保存到磁盘中,或者在网络中传输对象
这种机制就是使用一个字节序列表示一个对象,该字节序列包含:对象的类型、对象的数据和对象中存储的属性等信息。
字节序列写到文件之后,相当于文件中持久保存了一个对象的信息
反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反序列化
要实现序列化和反序列化就要使用对象序列化流和反序列化流:
- 对象序列化流:ObjectOutputStream
- 对象反序列化流:ObjectInputStream
例:对象序列化
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Demo06 {
public static void main(String[] args) throws IOException {
//对象序列化流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));
//创建对象
Student s = new Student("林青霞", 18);
//序列化对象
oos.writeObject(s); //NotSerializableException
//释放资源
oos.close();
}
}
例:对象反序列化
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Demo07 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\itcast\\oos.txt"));
//readObject
Object obj = ois.readObject();
Student s = (Student) obj;
System.out.println(s.getName() + "," + s.getAge());
//释放资源
ois.close();
}
}
import java.io.*;
public class Demo08 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
write();
read();
}
//反序列化
private static void read() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\itcast\\oos.txt"));
Object obj = ois.readObject();
Student s = (Student) obj;
System.out.println(s.getName() + "," + s.getAge());
ois.close();
}
//序列化
private static void write() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\itcast\\oos.txt"));
Student s = new Student("林青霞", 18);
oos.writeObject(s);
oos.close();
}
}
35.4 Properties
package myOtherStream;
import java.util.Properties;
import java.util.Set;
//Properties作为Map集合的使用
public class Demo09 {
public static void main(String[] args) {
//创建集合对象
// Properties<String,String> prop = new Properties();
Properties prop = new Properties();
//存储元素
prop.put("01", "林青霞");
prop.put("02", "张曼玉");
prop.put("03", "王祖贤");
//遍历集合
Set<Object> keySet = prop.keySet();
for (Object key : keySet) {
Object value = prop.get(key);
System.out.println(key + "," + value);
}
}
}
Properties特有方法
package myOtherStream;
import java.util.Properties;
import java.util.Set;
//Properties特有方法
public class Demo10 {
public static void main(String[] args) {
//创建集合对象
Properties prop = new Properties();
prop.setProperty("01", "林青霞"); //接收String类型 ,put是Object类型
prop.setProperty("02", "张曼玉");
prop.setProperty("03", "王祖贤");
//根据键获取值
// System.out.println(prop.getProperty("01"));
// System.out.println(prop.getProperty("04"));
// System.out.println(prop);
//获取键
Set<String> names = prop.stringPropertyNames();
for (String key : names) { //String类型,上个例子是Object类型
// System.out.println(key);
String value = prop.getProperty(key);
System.out.println(key + "," + value);
}
}
}
Properties和IO流相结合的方法
package myOtherStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
//集合中的数据保存到文件
public class Demo11 {
public static void main(String[] args) throws IOException {
//把集合在中的数据保存到文件
myStore();
//把文件中的数据加载到集合
myLoad();
}
private static void myLoad() throws IOException {
Properties prop = new Properties();
//load加载
FileReader fr = new FileReader("D:\\itcast\\fw.txt");
prop.load(fr);
fr.close();
System.out.println(prop);
}
private static void myStore() throws IOException {
Properties prop = new Properties();
prop.setProperty("01", "林青霞");
prop.setProperty("02", "张曼玉");
prop.setProperty("03", "王祖贤");
FileWriter fw = new FileWriter("D:\\itcast\\fw.txt");
prop.store(fw, null); //null指的是描述信息
fw.close();
}
}
案例:游戏次数
package myOtherStream;
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
private GuessNumber() {
}
public static void start() {
Random r = new Random();
int number = r.nextInt(100) + 1;
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你要猜的数字:");
int guessNumber = sc.nextInt();
//比较
if (guessNumber > number) {
System.out.println("你猜的数字大了");
} else if (guessNumber < number) {
System.out.println("你猜的数字小了");
} else {
System.out.println("恭喜你猜对了!");
break;
}
}
}
}
package myOtherStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class Demo12 {
public static void main(String[] args) throws IOException {
Properties prop = new Properties();
FileReader fr = new FileReader("D:itcast\\fw.txt");
prop.load(fr); //文件fr数据加载到集合prop
fr.close();
//通过Properties集合获取到玩游戏的次数
String count = prop.getProperty("count");
int number = Integer.parseInt(count);
//判断是否到3次
if (number >= 3) {
System.out.println("你的游戏次数已经用完!");
} else {
GuessNumber.start();
number++;
prop.setProperty("count", String.valueOf(number));
FileWriter fw = new FileWriter("D:\\itcast\\fw.txt");
prop.store(fw, null);
fw.close();
}
}
}