【黑马程序员】入学面试前的练习


立个贴,监督自己

 

节省时间,第二遍 只求继续看懂

如今这一遍也是最后一遍了,必须掌握代码了

 

对自己严格要求:

把视频里面毕老师强调掌握的代码和思路 默写三遍。

这一遍不图进度,只图 每一个代码 思路清晰。

 

每天的代码量  写过3遍的,贴到这个贴子里。

 

12.15  21:38分,开始   复习反射代码

 

首先写一个Person类,用于测试反射

 

package cn.itcast;

public class Person
{
	private String name;
	public int age;
	public Person(){}
	Person(String name)
	{
		this.name=name;
	}
	public Person(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	
	public void getName()
	{
		this.name=name;
	}
	
	public void getAge()
	{
		this.age=age;
	}
	
	public void helloReflect()
	{
		System.out.println("Hello Reflect,ok");
	}
	
	private void HelloTestPrivate()
	{
		System.out.println("Reflect private Method ok");
	}
	
	public  String toString()
	{
		return "Person name:"+"["+name+"]"+"Person age:"+"["+age+"]";
	}
}

 

练习三种获取字节码对象方式:

package cn.itcast;

public class ReflectDemo1 {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		//通过 静态方法 forName("配置文件类名");
		Class s1=Class.forName("cn.itcast.Person");
		//通过 类名.class
		Class s2=Person.class;
		
		//通过getClass方法
		Person p=new Person();
		Class s3=p.getClass();
		
		//判断字节码对象是否唯一
		System.out.println("s1=s2:"+(s1==s2));
		
		
	}

}

 

 

package cn.itcast;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

/*
 * 往Interger类型的集合中添加String数据
 */
public class TestFanxing {

	public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		// TODO Auto-generated method stub
		
		//创建集合
		ArrayList<Integer> array=new ArrayList<>();
		//获取字节码对象
		Class s=array.getClass();
		//获取ArrayList的add方法
		Method add=s.getMethod("add",Object.class);
		
		//调用Method的方法,添加元素 
		add.invoke(array, "黑马");
		add.invoke(array, "吴启华");
		add.invoke(array, "黎姿");
		add.invoke(array, "杨超凡");

		
			System.out.println(array);
		
	}

}
 


 

package cn.itcast2;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/*
 * 通过反射实例化Person对象
 * 这里有一个思考:
 * 		为什么使用Constructor的 newInstance()方法实例化 而不使用
 * 			Class的newInstance()方法实例化对象呢?
 * 
 * 			回答:因为Constructor的 newInstance(Object... initargs)方法 带参数
 */
public class Method2 {

	public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		// TODO Auto-generated method stub
		//获取Person类字节码对象
		Class<?> s=Class.forName("cn.itcast.Person");
		
		//调用Class的getConstruct(Class<?>...classe);
		Constructor c=s.getConstructor(String.class,int.class);
		
		//这个构造方法必须是公有的,否则不可以通过 Contstructor的方法 创建实例化对象
		//出现异常 NoSuchMedhodException,因为该构造方法没有设置为public,无声明默认protect
		//通过构造方法,获取实例对象
		Object obj=c.newInstance("黑马程序员",22);
		System.out.println(obj);
	}

}


 

package cn.itcast2;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import cn.itcast.Person;

/*
 * 获取Person类的
 *		构造方法 
 * 		公有方法【包括父类】
 * 		所有方法包括私有
 * 		
 * 		通过无参数的构造函数,创建一个Person对象
 * 		
 */
public class ReflectMethod1
{

	public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
	{
		// TODO Auto-generated method stub
		//创建Person类的字节码对象,
		Class s1=Class.forName("cn.itcast.Person");
		
		//通过字节码对象调用Class类的方法获取
		//用Method类的方法接收即可
	/*	
		Constructor[] cons=s1.getConstructors();
		for(Constructor con:cons)
		{
			System.out.println("公有构造函数是"+con);
		}
	*/	
		
		//区别getMehods()方法,获得公有方法,包括父类的
		//getDeclaredMehtods()获得本类所有方法
		Method[] methods=s1.getDeclaredMethods();
		//Method[] methods=s1.getMethods();
		for(Method method:methods)
		{
			System.out.println(method);
		}
		
		
		//获取无参构造函数
		Constructor c1=s1.getConstructor();
		Person p=(Person) c1.newInstance();
		System.out.println(p);
	}

}


 

package cn.itcast3;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/*
 * 暴力获取私有成员name并且改变值
 */
public class ForceReflect {

	public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		// TODO Auto-generated method stub
		
		Class s=Class.forName("cn.itcast.Person");
		//获取公有成员age
		Field age=s.getField("age");
		
		//获取私有成员name
		// java.lang.NoSuchFieldException,
		//Field name=s.getField("name");
		//必须通过Declare这个哦!
		Field name=s.getDeclaredField("name");
		
		Constructor con=s.getConstructor();
		
		Object obj=con.newInstance();
		age.set(obj, 29);
		
		//获取私有都这么难,怎么可能设置值这么简单呢?
		//直接设置,会报错:java.lang.IllegalAccessException
		//name.set(obj, name);
		
		//那么请记住Field中 的暴力访问!
		name.setAccessible(true);
		name.set(obj, "黎姿");
		
		System.out.println(obj);
	}

}


 

package cn.itcast3;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Test3 {

	public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		// TODO Auto-generated method stub
		Class s=Class.forName("cn.itcast.Person");
		
	/*	获取所有成员变量
		Field[] fields=s.getDeclaredFields();
		for(Field field:fields)
		{
			System.out.println(field);
		}
	*/	
		
		// 获取单个的成员变量
		Field age=s.getField("age");
		
		Constructor con=s.getConstructor();
		Object obj=con.newInstance();
		
		//Filed的set方法,对象是固定的,值是人为设定
		age.set(obj, 30);
		
		System.out.println(obj);
		
	}

}


今天晚上最后一道题目12.16日 凌晨1.44分

package cn.itcast;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

/*
 * 往Interger类型的集合中添加String数据
 */
public class TestFanxing {

	public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		// TODO Auto-generated method stub
		
		//创建集合
		ArrayList<Integer> array=new ArrayList<>();
		//获取字节码对象
		Class s=array.getClass();
		//获取ArrayList的add方法
		Method add=s.getMethod("add",Object.class);
		
		//调用Method的方法,添加元素 
		add.invoke(array, "黑马");
		add.invoke(array, "吴启华");
		add.invoke(array, "黎姿");
		add.invoke(array, "杨超凡");

		
			System.out.println(array);
		
	}

}


 

 

昨天的IO流部分代码练习

 

package cn.zifuliu.test;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/*
 * 练习两种读取方式
 */
public class TwoRead {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
		long start=System.currentTimeMillis();
//		readMethod1();//0毫秒
			readMethod2();//15毫秒
		long end=System.currentTimeMillis();
		System.out.println((end-start)+"毫秒");
	}
	
	//第二种方式:通过字符数组进行读取。
	public static void readMethod1() throws IOException
	{	
		//创建读取流对象
		FileReader fr=new FileReader("c:\\最近.txt");
		
		//定义一个字符数组。用于存储读到字符。
		//该read(char[])返回的是读到字符个数。
		char[] buf=new char[1024];
		int len=0;
		while((len=fr.read(buf))!=-1)
		{//把char型数组转换成字符串输出
			System.out.println(new String(buf,0,len));
		}
		/*
		 * 输出了最近.txt文件中的内容
		 */
	}
	//调用读取流对象的read方法。
	//read():一次读一个字符。而且会自动往下读。
	public static void readMethod2() throws IOException
	{
		//创建读取流对象
		FileReader fr=new FileReader("c:\\最近.txt");
		int ch=0;
		while((ch=fr.read())!=-1)
		{
			System.out.print((char)ch);
		}
		
	}

}



 

package cn.zifuliu.test;

import java.io.FileWriter;
import java.io.IOException;
/*
 * 字符流写入操作
 * read  
 * flush  close,区别。
 */
public class FileWriterTest {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
		//创建字符流 对象
		FileWriter fw=new FileWriter("c:\\haha.txt");
		
		//字符流write方法,写入一个字符串
		fw.write("i am very hayypy!");
		
		//字符流,数据光写入  还不行,只是写入到了流对象中
		//必须flush刷新一下,刷新到文件中去
		//把流中的内容刷新到文件中去
		fw.flush();
		fw.close();
		
	}

}


 

 

package cn.io.copy;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.management.RuntimeErrorException;
/*
 * 通过字符流缓冲区把一个.java文件复制成.txt文件
 * 缓冲技术原理:其实是在对象里面封装了数组,先把数据存储起来,
 * 	存完后一次性的操作 读写
 *	这也是面向对象的思想!提高效率!
 */
public class BufferCopytxt {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BufferedReader bfr=null;
		BufferedWriter bfw=null;
		try 
		{
			bfr=new BufferedReader(new FileReader("c:\\BufferedReaderDemo.java"));
			bfw=new BufferedWriter(new FileWriter("c:\\copyTxt.txt"));
			
			String lin=null;
			while((lin=bfr.readLine())!=null)
			{
				bfw.write(lin);
				bfw.newLine();//缓冲区中的方法newLine 换行
				System.out.println(lin);
			}
		} 
		catch (IOException e) 
		{
			// TODO: handle exception
			throw new RuntimeException("复制文件失败");
		}
		finally
		{
			try{
				bfr.close();
			}catch(IOException e)
			{
				throw new RuntimeException("读取文件失败");
			}
			try{
				bfw.close();
			}catch(IOException e)
			{
				throw new RuntimeException("写入文件失败");
			}
		}
	}

}


package cn.io.copy;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 *经过验证,可以赋值 txt  picture  MP3等文件格式
 * 将C盘的一个图片复制到D盘中
 * 读取 C盘的图片 inputStream
 * 写入 outputStream  到指定的D盘中
 * 关闭资源
 */
public class CopyPic {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		FileInputStream fis=null;
		FileOutputStream fos=null;
		try 
		{
			fis=new FileInputStream("c:\\最近5天任务.jpg");
			fos=new FileOutputStream("d:\\2.jpg");
			
			byte[] array=new byte[1024*1024];
			
			int length=0;
			
			while((length=fis.read(array))!=-1)
			{
				fos.write(array, 0, length);
			}
		} 
		catch (IOException e) 
		{
			// TODO: handle exception
			throw new RuntimeException("复制文件失败");
		}
		finally
		{
			try
			{
				if(fis!=null)
					fis.close();
			}
			catch(IOException e)
			{
				throw new RuntimeException("读取文件失败");
			}
			
			try
			{
				fos.close();
			}
			catch(IOException e)
			{
				throw new RuntimeException("写入文件失败");
			}
		}
	}

}


 

package cn.io.copy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
 * 复制一个MP3 测试 普通字节流读取写入的复制方法比较通过字节流缓冲区复制的方法时间
 */
public class CopyMp3 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		long start=System.currentTimeMillis();
//		cpoyMethod();//67800毫秒
		bufferCopy();//219毫秒,字节流缓冲区速度快
		long end =System.currentTimeMillis();
		System.out.println((end-start)+"毫秒");
	}

	private static void cpoyMethod() throws IOException
	{
		// TODO Auto-generated method stub
		FileInputStream fis=new FileInputStream("c:\\因为爱情.mp3");
		FileOutputStream fos=new FileOutputStream("c:\\王菲爱情.mp3");
		
		int len;
		while((len=fis.read())!=-1)
		{
			fos.write(len);
		}
		fis.close();
		fos.close();
	}
	
	private static void bufferCopy() throws IOException
	{
		 BufferedInputStream bufis=new BufferedInputStream(new FileInputStream("c:\\因为爱情.mp3"));
		 BufferedOutputStream bufos=new BufferedOutputStream(new FileOutputStream("c:\\Buffer爱情.mp3"));
		 
		 int len;
		 while((len=bufis.read())!=-1)
		 {
			 bufos.write(len);
		 }
		 bufis.close();
		 bufos.close();
	}
	

}


 

package cn.trans.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/*
 * 通过键盘录入,再从键盘输出
 * 要求使用转换流,
 * 把字节流转换成字符流使用字符流的缓冲区方法readLine读取一行的数据
 */
public class Test1 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		

		//获取键盘录入对象。
		//InputStream in = System.in;

		//将字节流对象转成字符流对象,使用转换流。InputStreamReader
		//InputStreamReader isr = new InputStreamReader(in);

		//为了提高效率,将字符串进行缓冲区技术高效操作。使用BufferedReader

		//BufferedReader bufr = new BufferedReader(isr);
		
		
		//使用转换流,把键盘输入输出字节流对象转换成字符流缓冲区对象
		BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bfw=new BufferedWriter(new OutputStreamWriter(System.out));
		//字符串lin用来接收每一行的数据
		 String lin=null;
		
		while((lin=bfr.readLine())!=null)
		{
			//人为设置跳出循环的条件
			if("over".equals(lin))
				break;
			
			//将读取到的数据,在写入的时候转换成大写
			bfw.write(lin.toUpperCase());
			bfw.newLine();
			
			bfw.flush();
			//这一步必须刷新写入流,否则,控制台不会输出内容
		}
		bfr.close();
	}

}

 


对象的序列化

 

package cn.object.test;

import java.io.Serializable;

public class Person implements Serializable
{
	public String name;
	public int age;
	public String cn;
	Person(String name,int age,String cn)
	{
		this.name=name;
		this.age=age;
		this.cn=cn;
	}
	public String toString()
	{
		return name+age+cn;
	}
}


 

package cn.object.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/*
 * 对象的序列化,就是把对象存储到硬盘中
 * 反序列化,就是读取硬盘中存储的对象数据
 */
public class Test1 {

	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		// TODO Auto-generated method stub
//		writeObject() ;
		readObject();
	}
	
	//使对象序列化,保存到硬盘上
	public static void writeObject() throws FileNotFoundException, IOException
	{
		
		ObjectOutputStream objos=new ObjectOutputStream(new FileOutputStream("c:\\objec.txt"));
		objos.writeObject(new Person("王菲",21,"中国"));
		objos.close();
	}
	//对象的反序列化,从硬盘中读取
	public static void readObject() throws FileNotFoundException, IOException, ClassNotFoundException
	{
		ObjectInputStream objis=new ObjectInputStream(new FileInputStream("c:\\objec.txt"));
		Person p=(Person)objis.readObject();
		System.out.println(p);
	}
	
}

 


装饰设计模式

 

package cn.zhuangshi.test;
/*
 * 装饰类
 * 装饰设计模式:
	当想要对已有的对象进行功能增强时,
	可以定义类,将已有对象传入,基于已有的功能,并提供加强功能。
	那么自定义的该类称为装饰类。
	
	比如给HashMap对象传递一个 Com类对象,自定义了比较器,使该集合具备需求自定义的比较性
	属于装饰设计模式
	
	装饰类通常会通过构造方法接收被装饰的对象。
	并基于被装饰的对象的功能,提供更强的功能。

	以前是通过继承将每一个子类都具备缓冲功能。
	那么继承体系会复杂,并不利于扩展。
	
	现在优化思想。单独描述一下缓冲内容。
	将需要被缓冲的对象。传递进来。也就是,谁需要被缓冲,谁就作为参数传递给缓冲区。
	这样继承体系就变得很简单。优化了体系结构。
	
	装饰模式比继承要灵活。避免了继承体系臃肿。
	而且降低了类于类之间的关系。
	
	装饰类因为增强已有对象,具备的功能和已有的是相同的,只不过提供了更强功能。
	所以装饰类和被装饰类通常是都属于一个体系中的。

 */
//被装饰类
class Person
{
	public void chifan()
	{
		System.out.println("喝酒");
	}
}
//装饰类,基于已有的功能提供增强的功能
class SuperPerson
{
	Person p;
	SuperPerson(Person p)
	{
		this.p=p;
	}
	public void chifan()
	{
		System.out.println("吃菜");
		p.chifan();
		System.out.println("划拳");
	}
}

public class Test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Person p=new Person();
		//将被装饰的类作为参数传递给装饰类
		//基于已有的功能提供更强的功能
		SuperPerson sp=new SuperPerson(p);
		sp.chifan();
	}

}

 


 

package cn.File.test;

import java.io.File;
import java.io.IOException;

public class TestFile {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
		//指定一个路径,可以是文件,可以文件夹,可以存在,也可以是不存在尾创建的
		File f1=new File("c:\\1.txt");//这只是一个File对象,
		System.out.println(f1.isDirectory());//false
		System.out.println(f1.isFile());//fasle
		
		
		f1.createNewFile();//调用File类的方法,创建一个文件
		System.out.println(f1.isFile());//true
		File f2=new File("c:\\1\\2.txt");// c:\\1.txt\\2.txt 不会创建
		//只要第一级目录是目录形式,后面的名字全是目录名,如果第一级目录 是1.txt,那么会创建失败
		//只要第一级目录为1或者其他名字 不带后缀名,那么 第二级目录2.txt也是一个目录名
		f2.mkdirs();//创建一个路径
		System.out.println(f2.isDirectory());//true
		
		File f3=new File("c:\\2.txt");
		System.out.println("f3的绝对路径:"+f3.getAbsolutePath()+"  f3存在吗?答: "+f3.exists());
		System.out.println(f3.getPath());
		
		
	}

}


 

 

 

递归

 

import java.io.File;

/*
列出指定目录下文件或者文件夹,包含子目录中的内容。
也就是列出指定目录下所有内容。

因为目录中还有目录,只要使用同一个列出目录功能的函数完成即可。
在列出过程中出现的还是目录的话,还可以再次调用本功能。
也就是函数自身调用自身。
这种表现形式,或者编程手法,称为递归。

递归要注意:
1,限定条件。

2,要注意递归的次数。尽量避免内存溢出。

*/
public class FileDigui {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File f=new File("f:\\");
		//showDir(f);//递归的时候容易发生空指针异常,因为数组装不下了!
	/*	int num=getNum(50);
		System.out.println(num);
		*/
		toBin(60);//111100  正确
	}
	public static void showDir(File f)
	{
		File[] dir=f.listFiles();
		for(int x=0;x<dir.length;x++)
		{
			if(dir[x].isDirectory())
					showDir(dir[x]);
			else
				System.out.println(dir[x]);
		}
	}
	public static int getNum(int n)
	{
		if(n==1)
			return n;
		return n+getNum(n-1);
	}
	
	public static void toBin(int n)
	{
		if(n>0)
		{
			toBin(n/2);
			System.out.print(n%2);
		}
	}
}


 

package cn.File.test;

import java.io.File;
import java.util.ArrayList;

public class DiguiTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File f1=new File("c:\\digui");
		ArrayList<File> list=new ArrayList<File>();
		fileToList(f1,list);
		System.out.println(list);
	}
	public static void fileToList(File dir,ArrayList<File> list)
	{
		File[] files=dir.listFiles();
		//关键是file指的是什么,指的是数组中的元素,元素包括 目录名和文件名
		for(File file:files)
		{
			//若是路径名,继续递归,不是路径名,就肯定是文件名,那么执行else语句
			if(file.isDirectory())
				fileToList(file,list);
			else
			{
				//file指的是数组中的元素,通过判断文件的名字 结尾,可以取出指定后缀的文件
				if(file.getName().endsWith(".java"))
					list.add(file);
			}
		}
	}

}

 

两道面试题

/*
 * 文件夹拷贝(文件内含有文件和文件夹)
 */
package cn.mianshi.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

/**
 * 思路:
 * 在主函数中,执行copy函数
 * 
 * 定义一个函数cpoy(src,des),  扫描当前路径下的文件,
 * 如果是目录,递归,如果是文件,调用另外一个函数copyfile()
 * 
 * 定义第二个函数copyfile(src,dex),用转换流,使用字符流的读取操作,读取文件
 *	用打印流,将file对象打印到指定目录下
 */
public class CopyDirectory {
	
	public static void main(String[] args) {
		copy("c:\\digui","E:\\myjava");
		System.out.println("文件拷贝完成!");
	}

	private static void copy(String src, String des) {
		File file1=new File(src);
		File[] fs=file1.listFiles();
		File file2=new File(des);
		if(!file2.exists()){
			file2.mkdirs();
		}
		for (File f : fs) {
			if(f.isFile()){
				fileCopy(f.getPath(),des+"\\"+f.getName()); //调用文件拷贝的方法
			}else if(f.isDirectory()){
				copy(f.getPath(),des+"\\"+f.getName());
			}
		}
		
	}

	/**
	 * 文件拷贝的方法
	 */
	private static void fileCopy(String src, String des) {
	
		BufferedReader br=null;
		PrintStream ps=null;
		
		try {
			br=new BufferedReader(new InputStreamReader(new FileInputStream(src)));
			ps=new PrintStream(new FileOutputStream(des));
			String s=null;
			while((s=br.readLine())!=null){
				ps.println(s);
				ps.flush();
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
				try {
					if(br!=null)  br.close();
					if(ps!=null)  ps.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
		}
		
		
	}

}


 

package cn.mianshi.test;
/*
 * 编写程序,将指定目录下所有.java文件拷贝到另一个目的中,并将扩展名改为.txt
 */

/*
 *思路:
 * 主函数执行 寻找该文件夹下的java文件 执行findAndCopyJava方法
 * 
 * findAndCopyJava函数:用于寻找 指定目录下的java文件
 * 		如果是目录,则递归,如果是文件,则调用copy方法,进行改名并且保存的操作
 *  copy函数:   用转换流, 进行一行的读取,提高效率
 *  			用打印流输出  File对象,提高效率
 *  			这里在打印流写入的时候,调用String类的replace方法
 *  			replace("元序列",目标序列") replace(".java",".txt"),
 *  
 */
import java.io.*;
public class Copytxt {
        public static void main(String[] args) {
                File orig=new File("C:\\digui"); //源文件夹
                File dest=new File("C:\\textdigui");//要复制过去的文件夹
                findAndCopyJava(orig,dest); 
                System.out.println("赋值并且改名成功!");
                
        }
        
        //用于改后缀后复制
        public static void copy(File orig,File dest)
        { 
                BufferedReader buf = null;
                PrintWriter  out=null;;
                try
                {
                        buf=new BufferedReader(new InputStreamReader(new FileInputStream(orig))); //读取流,提示阅读效率
                        out=new PrintWriter(dest+"\\"+orig.getName().replace(".java", ".txt"));  // 把后缀改成.java,用Print流提升效率
                }
                catch(IOException e)
                {
                        System.out.println("文件orig或者dest异常");
                }
               
                
                String line=null;
                try{
                while((line=buf.readLine())!=null)
                {
                        out.println(line);
                }
                
                }catch(IOException e)
                {
                        
                }
                finally{
                        try{
                                if(buf!=null)
                                        buf.close();
                                if(out!=null)
                                        out.close();
                        }catch(Exception e2){
                                
                        }
                }
        }
        //用于判断文件元素 是目录 还是。java文件
        public static void findAndCopyJava(File orig,File dest)
        {  //
                if(!dest.exists()){            //不存在就创建目的目录,但是这个地址有可能是一个绝对地址。
                        dest.mkdir();
                }
                if(!dest.isDirectory())
                {    //所以再次判断存在的文件是否是一个目录,而不是文件。
                        dest.mkdir();
                }
                //使用File方法 获得目标元 当前文件夹下的所有内容
                File[]  files=orig.listFiles();
               //对获得的 元素遍历,在循环中判断 是否为目录,是否为文件,是否为。java文件
                for(File file: files)
                {     //遍历files
                        if(file.isDirectory())
                        {
                                findAndCopyJava(file,dest);  //递归,一直到file是一个文件而不是目录。
                        }
                        else if(file.getName().endsWith(".java"))
                        {
                                copy(file,dest);
                        }
                }


        }
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值