递归解决问题的思路:
把一个复杂的问题层层转化为一个与原问题相似的规模较小的问题求解
少量的程序,就可以描述出接替过程中所需要的多次重复计算
递归解决问题要找到的两个内容:
例:遍历目录
需求给定一个路径(E:\itcast),请通过递归完成遍历该目录下的所有内容,并把所有文件的绝对路径输出到控制台
思路:
public class RecurveDemo {
public static void main(String[] args) {
File f = new File("/home/Id/");
recurve(f);
}
public static void recurve(File f){
File[] fs = f.listFiles();
for(File file : fs){
if(file.isFile()){
System.out.print(file.getAbsolutePath()+" ");
}else{
recurve(file);
}
}
}
}
字节流抽象类基类
package io;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
class OutputStreamDemo01 {
public static void main(String[] args) throws IOException {
/*
创建字节输出流对象,做了三件事
1.调用系统功能创建了文件
2.创建了字节输出流对象
3.让字节输出流对象指向创建好的文件
*/
FileOutputStream fos = new FileOutputStream("src/fos.txt");
fos.write(97);//a
fos.write(57);//‘9‘
fos.write(55);//‘7‘
//所有和IO相关的操作,最后都要释放资源
// close 关闭此文件输出流,并释放与此流相关联的任何系统资源
fos.close();
}
}
写数据步骤:创建对象,写数据,释放资源
byte[] bys = {97,98,99,100,101};
fos.write(bys);
//直接用String的getBytes方法方便,不需要记字符的ASCII码
byte[] bys1 = "abcde".getBytes();
fos.write(bys1);
fos.close();
finally:异常处理时提供清除操作,比如IO流中释放资源
特点:被finally控制的语句一定会执行,除非JVM退出
package io;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamDemo04 {
public static void main(String[] args) {
FileOutputStream fos =null;
try {
fos = new FileOutputStream("Z:\\src\\fos.txt");
fos.write("hello".getBytes());
}catch (IOException e){
e.printStackTrace();
}finally {
//在finally里释放资源,先做不为null判断,否则可能出现空指针异常
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
FileInputStream:从文件系统中的文件获取输入字节
int read() 读取一个字节数据
需求:把文件fos.txt的内容读取出来在控制台输出
public class FileInputStreamDemo01 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("src/fos.txt");
int by;
//读数据不需要换行,原文档含有换行符会被读取到,文档末尾字符是-1
while((by=fis.read())!=-1){
System.out.print((char)by);
}
fis.close();//释放资源
}
}
例 复制文本文件
思路:
1.根据数据源穿件字节输入流对象
2.根据目的地创建字节输出流对象
3.读写数据,赋值文本文件(一次读取一个字节,一次写入一个字节)
4.释放资源
public class CopyTxtDemo {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("src/fos.txt");
FileOutputStream fos = new FileOutputStream("a.txt");
int by;
while((by = fis.read())!=-1){
fos.write(by);
}
fos.close();
fis.close();
}
}
int read(byte[] b) 从该输入流读取最多 b.length个字节的数据为字节数组,返回值为读取的个数
package io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamDemo02 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("src/fos.txt");
byte[] bytes = new byte[5];
//第一次读取
int len = fis.read(bytes);
//读取的长度
System.out.println(len);
//将字节数组转化为字符串
System.out.println(new String(bytes));
//第二次读取
len = fis.read(bytes);
//读取的长度
System.out.println(len);
//将字节数组转化为字符串
System.out.println(new String(bytes));
//第三次读取
read = fis.read(bytes);
//读取的长度
System.out.println(read);
//将字节数组转化为字符串
System.out.println(new String(bytes));
/*
hello\r\n
world\r\n
第一次 hello
第二次 \r\nwor
第三次 ld\r\nr(r为上次存储的,这次只有4个字符,未被覆盖掉)
*/
fis.close();
}
}
实际输出应该读了几个输出几个字符,byte数组的大小应是1024的整数倍,每次输出都应换做如下写法:
byte[] bys = new byte[1024];//1024及其整数倍
int len;
while((len = fis.read(bys))!=-1){
System.out.print(new String(bys,0,len));//实际输出应该读了几个输出几个字符
}
字节缓冲流:
public class CopyAviDemo {
public static void main(String[] args) throws IOException {
long startTime = System.currentTimeMillis();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\拓新\\腾讯课堂java高级阶段资料.avi"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src/new.avi"));
byte[] bys = new byte[1024];
int len;
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
long endTime = System.currentTimeMillis();
System.out.println("共耗时"+(endTime-startTime)+"毫秒");
bos.close();
bis.close();
}
}
编码 String->byte:
public class ConversionStreamdemo {
public static void main(String[] args) throws IOException {
OutputStreamWriter osw =
new OutputStreamWriter(new FileOutputStream("src/fos.txt"),"GBK");
osw.write("果存");
osw.close();
int ch;
//用GBK编码的字符存入文件虽然我们看不懂,但是用编码规则的输入流可以读取里面的字符
InputStreamReader isr = new InputStreamReader(new FileInputStream("src/fos.txt"),"GBK");
//对于read方法此处一次读取的是一个字符,不再是一个字节
while((ch=isr.read())!=-1){
System.out.println((char)ch);
}
}
}
public class CopyJavaDemo1 {
public static void main(String[] args) throws IOException {
InputStreamReader isr= new InputStreamReader(new FileInputStream("src/io/OutputStreamWriterDemo.java"));
//new FileInputStream("src/io/OutputStreamWriterDemo.java"));
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("src/new.java"));
char[] cbuf = new char[1024];
int len;
while((len = isr.read(cbuf))!=-1){
osw.write(cbuf, 0, len);
osw.flush();
}
osw.close();
isr.close();
}
}
例:复制java文件改进版
public class CopyJavaDemo02 {
public static void main(String[] args) throws IOException {
FileReader fread = new FileReader("src/io/OutputStreamWriterDemo.java");
FileWriter fwrite = new FileWriter("src/new.java");
char[] cbuf = new char[1024];
int len;
while((len = fread.read(cbuf))!=-1){
fwrite.write(cbuf,0,len);
}
fwrite.close();
fread.close();
}
}
public class BufferedStreamDemo01 {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("src/writer.txt"));
bw.write("hello everyone\r\n");
bw.write("hello world\r\n");
bw.close();
}
}
BufferedWriter
public class BufferedStreamDemo02 {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("src/1.txt"));
for (int i = 0; i < 10; i++) {
bw.write("hello"+i);
// bw.write("\r\n"); 此换行符针对windows
bw.newLine();//使用newLine自适应操作系统换行符
bw.flush();
}
bw.close();
BufferedReader br = new BufferedReader(new FileReader("src/1.txt"));
String s;
while( (s = br.readLine())!=null){
System.out.println(s);//不读换行符号,要自己添加换行
}
br.close();
}
}
例:利用bufferedWriter/bufferedReader 特殊方法复制java文件
public class BufferedStreamDemo03 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("src/io/CopyAviDemo.java"));
BufferedWriter bw = new BufferedWriter(new FileWriter("new.java"));
String line;
while((line = br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
bw.close();
br.close();
}
}
例 集合到文件
需求:把ArrayList集合中的字符串数据写到文件中。要求:每个字符串元素作为文件中的一行数据
public class ArrayListToTxtDemo {
public static void main(String[] args) throws IOException {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("hello");
arrayList.add("world");
arrayList.add("java");
BufferedWriter bw = new BufferedWriter(new FileWriter("arr.txt"));
for(String s: arrayList) {
bw.write(s);
bw.newLine();
bw.flush();
}
bw.close();
}
}
同理 数据目的源也不一定是文件,可以把数据从文件读取到数组中去(使用bufferedReader)
例 点名器
需求:有一个文件里面存储了班级同学的姓名,没一个姓名占一行,要求通过程序实现随机点名
思路:将数据从文件读取到集合中,并释放流资源
随机产生0到集合长度的随机数,根据随机数找到索引对应的数据
public class CallNameDemo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("src/name.txt"));
ArrayList<String> names = new ArrayList<String>();
String line;
while((line = br.readLine())!=null){
names.add(line);
}
br.close();//重点
Random random = new Random();
int index = random.nextInt(names.size());//[0-size)之间的数
System.out.println(names.get(index));
}
}
例 把ArrayList集合中的学生数据写入到文本文件
把每个学生对象的数据作为文件中的一行数据,格式:学号,姓名,年龄,居住地 略
ArrayList从学生对象,拼接是使用StringBuilder
略
例 复制单级文件夹
需求:把“E:\itcast"把这个文件夹复制到模块目录下
思路:
1.创建数据源目录File对象,路径是E:\itcast
2.获取数据源目录File对象的名称(itcast)
3.创建目的地目录File对象,路径名是新的模块名+itcast组成
4.判断目的地目录对应的File是否存在,如果不存在就创建
5.获取数据源目录下所有文件的File数组
6.遍历File数组,得到每一个file对象,该File对象,其实就是数据源文件
7.获取数据源文件File对象名称
8.创建目的地文件File对象
9.复制文件(文件有文本,图片视频,采用二进制形式复制)
package io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFolderDemo {
public static void main(String[] args) throws IOException {
File source = new File("/home/userID/source");
File desination = new File("/home/userId/tmp");
String sourceName = source.getName();
//File dir = new File(desination.getPath()+"/"+sourceName);
File dir = new File(desination.getPath(),sourceName);
if(!dir.exists()){
dir.mkdirs();
}
String filename;
File desName;
File[] fileList = source.listFiles();
for(File file:fileList){
filename = file.getName();
//desName = new File(dir.getPath()+"/"+filename);
desName = new File(dir.getPath(),filename);
copyFile(file,desName);
}
System.out.println(sourceName);
}
public static void copyFile(File a, File b) throws IOException{
BufferedInputStream bis = new BufferedInputStream( new FileInputStream(a));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(b));
byte[] b1 = new byte[1024];
int len;
while((len=bis.read(b1))!=-1){
bos.write(b1, 0, len);
}
bos.close();
bis.close();
}
}
package io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class SystemInDemo {
public static void main(String[] args) throws IOException {
// InputStream is = System.in;
/*
int by;
while((by=is.read())!=-1){
System.out.print((char)by);
}*/
//如何把字节流转换为字符流?用转换流
//InputStreamReader isr = new InputStreamReader(is);
//使用字符流不能实现一次读取一行数据
//需要用缓冲流对字符流包装下,但是读取的是字符串
//BufferedReader br = new BufferedReader(isr);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("please input string");
String line = br.readLine();
System.out.println("the string is "+line);
//想要读取非字符串,要用包装类对其进行转换
System.out.println("please input int data");
int i = Integer.parseInt(br.readLine());
System.out.println("the string is "+i);
//自己写键盘录入太麻烦了,java提供Scanner
Scanner sc = new Scanner(System.in);
}
}
PrintStream ps = new PrintStream("fos.txt");
ps.write(97);
ps.print(98);
ps.println();
ps.println(48);
ps.close();
输出:
a98
48
package io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class CopyJavaDemo3 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("src/io/PrintStreamDemo.java"));
char[] cs = new char[1024];
String line;
PrintWriter pw = new PrintWriter(new FileWriter("src/collections/1.java"), true);
while((line =br.readLine())!=null){
pw.println(line);
}
pw.close();
br.close();
}
}
对象序列化:将对象保存在磁盘中,或者在网络中传输对象
使用一个字节序列表示一个对象,该字节序列包括:对象的类型,对象的数据和对象中存储的属性等信息
字节序列写到文件之后,相当于文件中持久保存了一个对象的信息
反之,该字节序列还可以从文件中读取回来重构对象,对它进行反序列化
要实现序列化和反序列化就要用对象序列化流和对象反序列化流
public class Student implements Comparable,Serializable {
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
...略
ObjectOutputSreamDemo.java
package io;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import collections.Student;
public class ObjectOutputStreamDemo {
public static void main(String[] args) throws FileNotFoundException, IOException {
ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream("src/io/oos.txt"));
Student s = new Student("xiaowang",21);
oos.writeObject(s);
oos.close();
}
}
NotSerializableException 抛出一个实例需要一个Serializable接口。 序列化运行时或实例的类可能会抛出此异常
类的序列化由实现java.io.Serializable接口的类启用。 不实现此接口的类将不会使任何状态序列化或反序列化( 序列化接口没有方法或字段,仅用于标识可串行化的语义)
public class ObjectInputStreamDemo {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/io/oos.txt"));
Student s = (Student)ois.readObject();
System.out.println(s.getName()+" is "+ s.getAge());
ois.close();
}
}
public class PropertiesDemo01 {
public static void main(String[] args){
// properties不同与map不能写泛型
// Properties<String,String> p = new Properties<String,String>();
Properties prop = new Properties();
prop.put("name1", "zhangsan");
prop.put("name2", "lisi");
prop.put("name3","wanger");
//按照集合的方式遍历properties,但注意返回的键和值都是Object类型
Set<Object> keySet = prop.keySet();
for(Object key : keySet){
System.out.println(key+" is "+prop.get(key));
}
}
}
public class PropertiesDemo02 {
public static void main(String[] args) throws IOException {
//myStore();
myLoad();
}
private static void myStore() throws IOException{
Properties prop = new Properties();
prop.setProperty("zhangsan", "24");
prop.setProperty("lisi", "29");
prop.setProperty("wangwu", "18");
prop.store(new FileWriter("src/1.txt"), "store");
}
private static void myLoad() throws FileNotFoundException, IOException{
Properties prop = new Properties();
prop.load(new FileReader("src/1.properties"));
Set<String> keySet = prop.stringPropertyNames();
for(String key : keySet){
System.out.println(key+" , "+prop.getProperty(key));
}
}
}
例2 猜数字小游戏,只能试玩3次。如果还想玩,提示试玩已结束,想玩请充值
1.写一个游戏类,里面有个猜数字的小游戏
2.写一个测试类,main()方法按下面步骤完成:
A.从文件中读取数据到Properties集合,用load()方法实现
文件已存在:game.txt里面数据count=0(注意map的格式等于)
B.通过Properties集合获取到玩游戏的次数
C.判断次数是否到达3次
如果到了,给出提示,游戏试玩已经输,想玩请充值
如果不到3次
玩游戏
次数+1,重新写回文件,用Properties的store()方法实现
Game.java
package io;
import java.util.Random;
import java.util.Scanner;
public class Game {
public static void play(){
Random random = new Random();
int value = random.nextInt(10)+1;
System.out.println("please guess the number from 1~ 10");
while(true){
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
if(input>value){
System.out.println("your input is bigger");
}else if(input<value){
System.out.println("your input is smaller");
}else{
System.out.println("Success"+value+"="+input);
break;
}
}
}
}
TestGame.java
package io;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class TestGame {
public static void main(String[] args) throws FileNotFoundException,
IOException {
Properties prop = new Properties();
FileReader fr = new FileReader("src/game.txt");
prop.load(fr);
fr.close();// 注意关闭流close!!!
int count = Integer.parseInt(prop.getProperty("count"));
boolean trival = true;
if (count >=3 && trival) {
System.out
.println("have tried 3 times,please buy it www.baiduChargeMoney.com");
} else {
Game.play();
}
count++;
prop.setProperty("count", String.valueOf(count));
FileWriter fw = new FileWriter("src/game.txt");
prop.store(fw, null);
fw.close();
}
}
原文:https://www.cnblogs.com/drying-net/p/14658656.html