IO流部分案例总结

IO流部分案例总结


1.Exception
A:throws和throw的区别
throws: 用在方法申明后面,跟的是异常类名,可以跟多个异常类名,用逗号隔开
表示抛出异常,由该方法的调用者来处理
表示出现异常的一种可能性,并一不定会发生这些异常
throw: 用在方法体内,跟的是异常对象名,只能抛出一个异常对象名
表示抛出异常,有方法体内的语句处理
执行throw则一定抛出了某种异常

B:final、finally、finalize的区别
final: 最终的意思,可以修饰类、成员变量、成员方法
被修饰的类不能被继承、被修饰的变量是常量、被修饰的方法不能被重写
finally:是异常处理的一部分,用于释放资源
在执行到finally之前若JVM未停止,则finally一定会被执行
finalize:是Object类的一个方法,用于垃圾回收


2.File
A:构造方法
File(String pathname):根据一个路径得到File对象
File(String parent,String child):根据一个目录和一个子文件/目录得到File对象
File(File parent,String child):根据一个父File对象和一个子文件/目录得到File对象
B:常用成员方法
a:创建功能
public boolean createNewFile():创建文件,如果文件存在,则不执行任何操作
public boolean mkdir():创建文件夹,如果该文件夹存在,则不执行创建操作
public boolean mkdirs():创建多级文件夹,如果父文件夹不存在,则同时创建父文件夹
b:删除功能
public boolean delete():注意:文件夹为空文件夹的时候才能删除
c:重命名/剪切功能
public boolean renameTo(File dest):路径相同为重命名,路径不同为重命名并剪切
d:判断功能
public boolean isDirectory():判断是否为目录
public boolean isFile():判断是否为文件
public boolean exists():判断是否存在
public boolean canRead():判断是否可读
public boolean canWrite():判断是否可写
public boolean isHidden():判断是否隐藏
e:获取功能
public String[] list():获取指定目录下所有文件和文件夹的名称数组
public File[] listFiles():获取指定目录下的所有文件和文件夹的File数组
public String getAbsolutePath():获取绝对路径
public String getPath():获取相对路径
public String getName():获取名称
public long length():获取长度,字节数
public long lastModified():获取最后一次修改的时间,毫秒值
f:文件名称过滤器
public String list(FilenameFilter filter)
public File[] listFiles(FilenameFilter filter)

C:判断E盘中是否存在后缀名为".jpg"的文件,有就输出文件名称
a:普通方法
File file = new File("E:\\");
File[] fileArray = file.listFiles();
for(File f : fileArray){
if(f.isFile()){
if(f.getName().endsWith(".jpg")){
System.out.println(f.getName());
}
}
}

b:使用文件名称过滤器
File file = new File("E:\\");
String[] strArray = file.list(new FilenameFilter(){
public boolean accept(File dir,String name){
return new File(dir,name).isFile() && name.endsWith(".jpg");
}
});
for(String s : strArray){
System.out.println(s);
}

D:批量修改文件名称
修改前:E:\评书\三国演义\三国演义_001_[评书网]_桃园三结义.avi
修改后:E:\评书\三国演义\001_桃园三结义.avi
//封装目录
File folder = new File("E:\\评书\\三国演义");
File[] fileArray = folder.listFiles();
for(File file : fileArray){
//获得名称,配合索引截取字符串,拼接生成新名称
String oldName = file.getName();
int index1 = oldName.indexOf("_");
String str1 = oldName.substring(index1 + 1,index2 + 4);
ing index2 = oldName.lastIndexOf("_");
String str2 = oldName.substring(index2);
String newName = str1.concat(str2);
//封装新目录
File newFile = new File(folder,newName);
//重命名
file.renameTo(newFile);
}

3.递归
A:不死神兔问题(第二是个月兔子的对数?)
a:操作数组实现
int[] arr = new int[20];
int[0] = 1;
int[1] = 1;
for(int x = 2;x < arr.length; x++){
arr[x] = arr[x -1] + arr[x - 2];
}
int result = arr[19];

b:普通实现
int a = 1;
int b = 1;
for(int x = 0;x < 18; x++){
int temp = a;
a = b;
b = temp + a;
}
int result = b;

c:递归实现
public atatic int getNum(int i){
if(i == 1 || i == 2){
return 1;
}else{
return getNum(n - 1) + getNum(n - 2);
}
}

B:输出指定目录(E:\Java)下指定后缀名文件(.java)的绝对路径
File folder = new File("E:\\JavaSE");
getAllJavaFilePaths(folder);

public static void getAllJavaFilePaths(File folder){
File[] fileArray = folder.listFiles();
for(File file : fileArray){
if(file.isDirectory()){
getAllJavaFilePaths(file);
}else{
if(file.getName().endsWith(".java")){
System.out.println(file.getAbsolutePath());
}
}
}

}

C:删除非空目录
File folder = new File("demo");
deleteFolder(folder);

private static void deleteFolder(File folder){
File[] fileArray = folder.listFiles();
if(fileArray != null){
for(File file : fileArray){
if(file.isDirectory()){
deleteFolder(file);
}else{
System.out.println(file.getName());
file.delete();
}
}
System.out.prinltn(folder.getName());
folder.delete();
}

}

4.字节流
A:创建字节输出流对象做了几件事情
a:调用系统功能创建文件
b:创建字节输出流对象
c:把字节输出流对象指向这个文件

B:字节流复制音频的四种方式
method("E:\\abc.mp3","D:\\abc.mp3");

a:基本字节流一次读写一个字节
public static void method(String srcString,String destString) throws IOException {
FileInputStream fis = new FileInputStream(srcString);
FileOutputStream fos = new FileOutputStream(destString);
int by = 0;
while((by = fis.read()) != -1){
fos.write(by);
}
fos.close();
fis.close();
}

b:基本字节流一次读写一个字节数组
public static void method(String srcString,String destString) throws IOException {
FileInputStream fis = new FileInputStream(srcString);
FileOutputStream fos = new FileOutputStream(destString);
byte[] bys = new byte[1024];
int len = 0;
while((len = fis.read(bys)) != -1){
fos.write(byte,0,len);
}
fos.close();
fis.close();
}

c:高效字节流一次读写一个字节
public static void method(String srcString,String destString) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcString));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destString));
int by = 0;
while((by = bis.read()) != -1){
bos.write(by);
}
bos.close();
bis.close();
}

d:高效字节流一次读写一个字节数组
public static void methed(String srcString,String destString) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcString));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destString));
byte[] bys = new byte[1024];
int len = 0;
while((len = bis.read(bys)) != -1){
bos.write(bys,0,len);
}
bos.close();
bis.close();
}

5.字符流
A:字节流复制文本文件的5中方式
method("E:\\aaa.txt","D:\\bbb.txt");

a:基本字符流一次读写一个字符
private static void method(String srcString,String destString) throws IOException{
FileReader fr = new FileReader(srcString);
FileWriter fw = new FileWriter(destString);
int ch = 0;
while((ch = fr.read()) != -1){
fw.write(ch);
}
fw.close();
fr.close();
}

b:基本字符流一次读写一个字符数组
private static void method(String srcString,String destString) throws IOException {
FileReaer fr = new FileReader(srcString);
FileWriter fw = new FileWriter(destString);
char[] chs = new char[1024];
int len = 0;
while((len = fr.read(chs)) ! = -1){
fw.write(chs,0,len);
}
fw.close();
fr.close();
}

c:字符缓冲流一次读写一个字符
private static void method(String srcString,String destString) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(srcString));
BufferedWriter bw = new BufferedWriter(new FileWriter(destString));
int ch = 0;
while((ch = br.read()) != -1){
bw.write(ch);
}
bw.close();
br.close();
}

d:字符缓冲流一次读写一个字符数组
private static void method(String srcString,String destString) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(srcString));
bufferedWriter bw = new BufferedWriter(new FileWriter(destString));
char[] chs = new char[1024];
int len = 0;
while((len = br.read(chs)) != -1){
be.write(chs,0,len);
}
bw.close();
br.close();
}

e:字符缓冲流一次读写一个字符串(一行)
private static void method(String srcString,String destString) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(srcString));
BufferedWriter bw = new BufferedWriter(new FileWriter(destString));
String line = null;
while((line = br.readLine()) != null){
bw.write(line);
bw.newLine();
bw.flush();
}
bw.close();
br.close();
}

6.IO流综合练习
A:把集合中的数据存储到文本文件中
ArrayList<String> array = new ArrayList<String>();
array.add("hello");
array.add("world");
BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\a.txt"));
for(String str : array){
bw.write(str);
bw.newLine();
bw.flush();
}
bw.close();

B:把文本文件中的数据读取到集合中并遍历集合
BufferedReader br = new BufferedReader(new FileReader("a.txt"));
ArrayList<String> array = new ArrayList<String>();
String line = null;
while((line = br.readLine()) != null){
array.add(line);
}
br.close();
for(String str : array){
Syste.out.println(str);
}

C:复制指定目录下的指定文件,并修改后缀名
//封装目录
File srcFolder = new File("E:\\Java");
File destFolder = new File("D:\\Jad");
//如果目的地不存在则创建
if(!destFolder.exists()){
destFolder.mkdir();
}
//从数据源获取指定文件名添加到文件数组中
File[] fileArray = srcFolder.listFiles(new FilenameFilter(){
public boolean accept(File dir,String name){
return new File(dir,name).isFile() && name.endsWith(".java");
}
});
//遍历数组得到新路径并复制文件
for(File file : fileArray){
String neme = file.getName();
File newFile = new File(destFolder,name);
coptyFile(file,newFile);
}
//在目的地目录下完成文件名称修改
File[] destFileArray = destFolder.listFiles();
for(File destFile : destFileArray){
String name = destFile.getName();
String newName = name.replace(".java",".jad");
File newFile = new File(sestFolder,newName);
destFile.renameTo(newFile);
}
//复制文件的方法
private static void copyFile(File file,File newFile) throws IOException {
BufferedInputStrean bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream  bos = new BufferedOutputStream(new FileOutputStream(newfile));
byte[] bys = new byte[1024];
int len = 0;
while((len = bis.read(bys)) != -1){
bos.write(bys,0,len);
}
bos.close();
bis.close();
}

D:复制多级文件夹
//封装目录
File srcFolder = new File("E:\\JavaSE");
File destFolder = new File("D:\\");
copyFolder(srcFolder,destFolder);
//创建新目录路径,复制文件夹,创建文件路径
private static void copyFolder(File srcFolder,File destFolder) throws IOException {
if(srcFolder.isDirectory()){
File newFolder = new File(destFolder,srcFolder.getName());
newFolder.mkdir();
File[] fileArray = srcFolder.listFiles();
for(File file : fileArray){
copyFolder(file,newFolder);
}
}else{
File newFile = new File(destFolder,srcFolder.getName());
copy(srcFolder,newFile);
}
}
//复制文件
private static void copyFile(File srcFolder,File newFile) throw IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFolder));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while((len = bis.read()) != -1){
bos.write(bys,0,len);
}
bos.close();
bis.close();

}

E:键盘录入5个学生信息,按照总分从高到低存储到文本文件
//在Student类中写出getSum()方法
public int getSum(){
return this.chinese + this.math + this.english;
}
//测试类中完成下列代码
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>(){
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.getEnglish() - s2.getEnglish() : num3;
int num5 = num4 == 0? s1.getName.compareTo(s2.getName()) : num4;
return num5;
}
});

for(int x = 0; x < 5; x++){
键盘录入学生信息
创建学生对象
将学生对象添加为集合元素
}

BufferedWriter bw = new BufferedWriter(new FileWriter("Student.txt"));
bw.write("学生信息如下:");
bw.newLine();
bw.flush();
bw.write("姓名 语文成绩 数学成绩 英语成绩");
bw.newLine();
bw.flush();
for(Student s : ts){
StringBuilder sbu = new StringBuilder();
sbu.append(s.getName()).append(" ").append(s.getChinese()).append(" ")
.append(s.getMath()).append(" ").append(s.English);
bw.write(sbu.toString());
bw.newLine();
bw.flush();
}
bw.close();
System.out.println("学生信息存储完毕!");

F:用Reader模拟BufferedReader的特有功能
public class MyBufferedReader{
private Reader r;
public MyBufferedReader(Reader r){
this.r = r;
}
public String readLine() throws IOException {
StringBuilder sbu = new StringBuilder();
int ch = 0;
while((ch = r.read()) != -1){
if(ch = '\r'){
continue;
}
fi(ch == '\n'){
return return sbu.toString;
}else{
sbu.append((char)ch);
}
}
if(sbu.length() > 0){
return sbu.toString();
}
return null;
}
public void close() throws IOException {
this.r.close();
}
}
//测试类
MyBufferedReader mbr = new MyBufferedReader(new FileReader("aaa.txt"));
String line = null;
while((line = mbr.readLine()) != null){
System.out.println(line);
}
mbr.colse();

7.字符转换流的理解
字符读入转换流
InputStreamReader = FileInputStream + 编码表
FileReader = FileInputStream + 编码表
字符写出转换流
OutputStreamWriter = FileOutputStream + 编码表 
FileWriter = FileOutputStream + 编码表

8.打印流
A:  字节打印流:printStream
字符打印流:printWriter
B:能直接对文本文件操作的流对象
FileInputStream
FileOutputStream
FileReader
FileWriter
PrintStream
PrintWriter
C:打印流的自动刷新功能
PrintWriter pw = new PrintWriter(new FileWriter("aaa.txt"),true);
必须配合println()方式使用才可以,可同时实现自动刷新和换行的功能
此时println()等价于bw.write(); bw.newLine(); bw.flush();

D:使用打印流实现文件复制
BufferedReader br = new BufferedReader(new FileReader("aaa.txt"));
PrintWriter pw = new PrintlnWriter(new FileWriter("bbb.txt"));
String line = null;
while((line = br.readLine()) != null){
pw.println(line);
}
pw.close();
br.close();

9.标准输入输出流
A: in 标准输入流的使用
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入一个字符串:");
String line = br.readLine();

System.out.println("请输入一个整数:");
line = br.readLine();
int i = Integer.parseInt(line);

B: out 标准输出流的使用
原理:
System.out.println("hello");

PrintStream ps = System.out;
ps.println("hello");

使用:
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
bw.write(line);

10.序列化流
序列化流:把对象按照流一样的方式存入文本文件或者在网络中传输
 对象 --- 流数据(ObjectOutputStream)
反序列化流:把文本文件中的对象数据或者网络中的流对象数据还原成对象
  流数据 --- 对象(ObjectInputStream)
  
案例:
public class Person implements Serializable {
private static final long serialVersionUID = -2071565876962058344L;
private String name;
private transient int age; //使用transient修饰表示不被序列化

....
}
测试类
write();
read();

private static void read() throws IOException,ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));
Object obj = ois.readObject();
ois.close();
}

private static void writ() throws IOException{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));
Person p = new Person("盖聂",40);
oos.writeObject(p);
oos.close();
}

11.Properties

Properties是一个集合类,Hashtable的子类
A:特有功能
public Object setProperty(String key,String value):添加数据
public String getProperty(String key):根据键找值
public Set<String> stringPropertyNames():返回键的集合

B:和IO流结合使用的方法
把键值对形式的文本文件内容加载到集合中
public void load(Reader reader)
public void load(InputStream inStream)


把集合中的数据存储到文本文件中
public void store(Writer writer,String comments)
public void store(OutputStream out,String comments)

C:根据给定的文本文件判断是否有键为:"盖聂",如果有就修改其值为:"卫庄"
Properties prop = new Properties();
Reader r = new FileReader("user.txt");
prop.load(r);
r.close();

Set<String> set = prop.StringPropertyNames();
for(String key : set){
if("盖聂".equals(key)){
prop.setProperty(key,"卫庄");
break;
}
}

Writer w = new FileWriter("user.txt");
prop.store(w,null);
w.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值