1、File类常见方法:
1)创建
boolean creatNewFile():在指定位置创建文件,如果该文件已经存在,则不创建,返回false。和输出流不一样,输出流对象一建立就创建文件,而且文件已经存在,会覆盖。
boolean mkdir():创建一级目录,如果不存在返回true创建成功,如果存在返回false创建失败
boolean mkdir():可创建多级目录
2)删除
boolean delete();//删除失败返回false
void deleteOnExit();//在程序退出时删除指定文件
3)判断
boolean canExecute():判断文件是否可执行
boolean exists():文件是否存在
isFile();判断是否为文件//需要特别注意:文件名不能与目录名同名(创建不了)。判断之前必须先做是否存在的判断用exists()
isDirectory();判断是否为目录
isHidden();判断是否为隐藏
isAbsolute():是否是绝对路径,即便文件不存在也可判断
4)获取信息
getName();
getPath();
getParent();//获取父目录。注意:该方法返回的是绝对路径中的父目录,如果获取的是相对路径,返回null;如果相对路径中有上一层目录那么该目录就是返回结果。
getAbsolutePath();
lastModified();//返回最后一次修改时间
length()
- public class FileDemo1 {
- public static void main(String[] args) throws IOException{
- //consMethod();
- method_5();
- }
- public static void method_5(){
- File f1 = new File("c:\\1.txt");
- File f2 = new File("c:\\2.txt");
- System.out.println(f1.renameTo(f2));
- }
- public static void method_4(){
- File f = new File("1.txt");
- System.out.println("path:"+f.getPath());
- System.out.println("Abspath:"+f.getAbsolutePath());
- System.out.println("parent:"+f.getParent());//该方法返回的是绝对路径中的父目录,如果获取的是相对路径,返回null
- //如果相对路径中有上一层目录那么该目录就是返回结果。
- }
- public static void method_3() throws IOException {
- File f = new File("2.txt");
- System.out.println("mkdir:"+f.mkdirs());
- //在判断文件对象是否是文件或者目的时,必须要先判断该文件对象封装的内容是否存在,用exists判断
- System.out.println("dir:"+f.isDirectory());
- System.out.println("file:"+f.isFile());
- System.out.println(f.isAbsolute());//判断是否为绝对路径
- }
- public static void method_2() throws IOException {
- //File f = new File("demo.txt");
- //System.out.println("exists:"+f.exists());//判断文件是否存在
- //System.out.println("execute:"+f.canExecute());//判断文件是否可执行
- File dir = new File("abc\\1");
- System.out.println("mkdir:"+dir.mkdirs());
- }
- public static void method_1() throws IOException {
- File f = new File("file.txt");
- System.out.println("create:"+f.createNewFile());
- //System.out.println("mkdir:"+f.mkdirs());文件名不能与目录名同名
- //f.deleteOnExit();
- }
- public static void consMethod() {
- //将txt封装成file对象 ,可以将已有的和未出现的文件或文件夹封装成对象。
- File f1 = new File("c:\\abc\\a.txt");
- File f2 = new File("c:\\abc","b.txt");
- File d = new File("c:\\abc");
- File f3 = new File(d,"d.txt");
- //关联的相对路径则打印结果为相对路径,关联的是绝对路径则打印结果为绝对路径。
- System.out.println("f1:"+f1);
- System.out.println("f2:"+f2);
- System.out.println("f3:"+f3);
- //System.out.println("d:"+d);
- //File.separator是可以跨平台识别的分隔符
- File f4 = new File("c:"+File.separator+"abc"+File.separator+"zzz"+File.separator+"a.txt");
- }
- }
2、static listRoots():静态方法,返回根目录盘符数组File[ ]files
list:返回指定目录下的所有文件名,包含隐藏文件。调用list方法的file对象必须是封装了一个目录,该目录还必须存在。
- public class FileDemo2 {
- public static void main(String[] args) {
- //listRootsDemo ();
- //listDemo();
- File dir = new File("c:\\");
- File[] files = dir.listFiles();
- for(File f : files) {
- System.out.println(f.getName()+"::"+f.length());
- }
- }
- public static void listDemo2(){
- File dir = new File("c:\\");
- String[] arr = dir.list(new FilenameFilter(){
- public boolean accept(File dir,String name) {
- return name.endsWith(".txt");
- }
- });
- System.out.println(arr.length);
- for(String name : arr) {
- System.out.println(name);
- }
- }
- public static void listDemo(){
- File f =new File("d:\\");
- String[] names = f.list();
- for (String name : names) {
- System.out.println(name);
- }
- }
- public static void listRootsDemo (){
- File[] files = File.listRoots();
- for(File f : files) {
- System.out.println(f);
- }
- }
- }
3、递归:自己调用自己
递归要注意:
1)限定条件
2)要注意递归的次数,尽量避免内存溢出
- //列出指定目录下文件或文件夹,包含子目录中的内容,也就是列出指定目录下所有内容
- /*
- 因为目录中海油目录,只要使用同一个列出目录功能的函数完成即可
- 在列出过程中出现的还是目录的话,还可以再次调用本功能
- 也就是函数自身调用自身
- 这种表现形式,或编程手法,成为递归
- 递归要注意:
- 1、限定条件
- 2、要注意递归的次数,尽量避免内存溢出
- */
- public class FileDemo3 {
- public static void main(String[] args) {
- File dir = new File("d:\\javatest");
- //showDir(dir);
- //toBin(6);
- System.out.println(getSum(100));
- }
- public static int getSum(int n) {
- if(n==1)
- return 1;
- return n+getSum(n-1);
- }
- public static void toBin (int num){
- if (num>0) {
- toBin(num/2);
- System.out.print(num%2);
- }
- }
- public static void showDir(File dir) {
- System.out.println("path::"+dir.getPath());
- File[] files = dir.listFiles();
- for (int x= 0; x<files.length;x++) {
- if(files[x].isDirectory()) {
- showDir(files[x]);
- }
- else
- System.out.println(files[x]);
- }
- }
- }
- public static String getLevel(int level) {
- StringBuilder sb = new StringBuilder();
- sb.append("|--");
- for(int x=0; x<level;x++) {
- //sb.append("|--");
- sb.insert(0, " ");
- }
- return sb.toString();
- }
- public static void showDir2(File dir,int level) {
- System.out.println(getLevel(level)+dir.getName());
- level++;
- File[] files2 = dir.listFiles();
- for(int x=0; x<files2.length;x++) {
- if(files2[x].isDirectory())
- showDir2(files2[x],level);
- else
- System.out.println(getLevel(level)+files2[x].getName());
- }
- }
4、练习
- //删除一个带内容的目录
- /*
- 删除原理:在windows中,删除目录从里面往外删除的
- 既然是从里往外删除,就需要用到递归
- */
- public class RemoveDirDemo {
- public static void main(String[] args) {
- File dir = new File("d:\\test");
- removeDir(dir);
- }
- public static void removeDir(File dir) {
- File[] files = dir.listFiles();
- for(int x=0;x<files.length;x++) {
- if(files[x].isDirectory())
- removeDir(files[x]);
- else
- System.out.println(files[x].toString()+":-file-:"+files[x].delete());
- }
- System.out.println(dir+"::dir::"+dir.delete());
- }
- }
5、练习:将一个指定目录下的java文件的绝对路径,存储到一个文本文件中
- //将一个指定目录下的java文件的绝对路径,存储到一个文本文件中
- //建立一个java文件列表文件
- /*
- 思路:
- 1、对指定的目录进行递归
- 2、获取递归过程所有的java文件的路径
- 3、将这些路径存储到集合中。
- 4、将集合中的数据写入到一个文件中
- */
- public class JavaFileListDemo {
- public static void main(String[] args) {
- File dir = new File("d:\\test");
- List<File> list = new ArrayList<File> ();
- fileToList(dir,list);
- File file = new File(dir,"javalist.txt");
- writeToFile(list,file.toString());
- }
- public static void writeToFile(List<File> list,String javaListFile) {
- BufferedWriter bufw = null;
- try {
- bufw = new BufferedWriter(new FileWriter(javaListFile));
- for(File f : list) {
- String path = f.getAbsolutePath();
- bufw.write(path);
- bufw.newLine();
- bufw.flush();
- }
- }catch (IOException e ) {
- throw new RuntimeException("shibai");
- }
- finally {
- try {
- if(bufw!=null)
- bufw.close();
- }catch(IOException ex) {
- throw new RuntimeException("shibai");
- }
- }
- }
- public static void fileToList(File dir,List<File> list) {
- File[] files = dir.listFiles();
- for(File file : files) {
- if (file.isDirectory()){
- fileToList(file,list);
- }
- else {
- if(file.getName().endsWith(".java"))
- list.add(file);
- }
- }
- }
- }
6、Properties
是Hashtable的子类,具备map集合的特点,而且它里面存储的键值对都是字符串。
是集合中和IO技术想结合的集合容器。
该对象的特点:可以用于键值对形式的配置文件。
在加载数据时,需要有固定格式:键=值。- public static void main(String[] args) throws IOException{
- //setAndGet();
- // method_1();
- loadDemo();
- }
- //演示,如何将流中的数据存储到集合中
- //想要将info.txt中的键值数据存到集合中进行操作
- /*
- 1、用一个流和info.txt文件关联
- 2、读取一行数据,将该行数据用"="进行切割
- 3、等号左边作为键,右边作为值,存入到Properties集合中即可
- */
- public static void loadDemo() throws IOException{
- Properties prop = new Properties();
- FileInputStream fis = new FileInputStream("d:\\test\\infotest.txt");
- //将流中的数据加载进集合
- prop.load(fis);
- prop.setProperty("wangwu", "39");
- FileOutputStream fos = new FileOutputStream("d:\\test\\infotest.txt");
- prop.store(fos, "hah");
- //System.out.println(prop);
- prop.list(System.out);
- }
- public static void method_1() throws IOException{
- BufferedReader bufr = new BufferedReader(new FileReader("d:\\test\\infotest.txt"));
- String line = null;
- Properties prop = new Properties();
- while((line=bufr.readLine())!=null) {
- String[] arr = line.split("=");
- prop.setProperty(arr[0], arr[1]);
- // System.out.println(arr[0]+"...."+arr[1]);
- }
- bufr.close();
- System.out.println(prop);
- }
- //设置和获取元素
- public static void setAndGet() {
- Properties prop = new Properties();
- prop.setProperty("zhangsan","30");
- prop.setProperty("lisi","39" );
- // System.out.println(prop);
- String value = prop.getProperty("lisi");
- // System.out.println(value);
- prop.setProperty("lisi", 89+"");
- Set<String> names = prop.stringPropertyNames();
- for(String s : names) {
- System.out.println(s+":"+prop.getProperty(s));
- }
- }
- }
- /*
- 用于记录应用程序运行次数,如果使用次数已到,那么给出注册提示
- 很容易想到的是:计数器。可是该计数器定义在程序中,随着程序的运行而在内存中存在,并进行自增,随着该应用程序的退出,该计算器也在内存中消失了。
- 下一次在启动该程序,又重新开始从0计数,这样不是我们想要的。
- 程序即使结束,该计数器的值也存在。下次程序启动在会先加载该计数器的值并加1后再重新存储起来。
- 所以要建立一个配置文件,用于记录该软件的使用次数。
- 该配置文件使用键值对的形式,这样便于阅读数据,并操作数据。
- 键值对数据是map集合,数据是以文件形式存储,使用io技术,那么map+io-->properties
- 配置文件可以实现应用程序数据的共享。
- */
- public class PropertiesDemo2 {
- public static void main(String[] args) throws IOException{
- Properties prop = new Properties();
- File file = new File("d:\\test\\count.ini");
- if(!file.exists()) {
- file.createNewFile();
- }
- FileInputStream fis = new FileInputStream(file);
- prop.load(fis);
- int count = 0;
- String value = prop.getProperty("time");
- if(value!=null){
- count = Integer.parseInt(value);
- if(count>=5){
- System.out.println("您好,使用次数已到,拿钱!");
- return;
- }
- }
- count++;
- prop.setProperty("time",count+"");
- FileOutputStream fos = new FileOutputStream(file);
- prop.store(fos, "");
- fis.close();
- fos.close();
- }
- }
8、打印流:该流提供了打印方法,可以将各种数据类型的数据都原样打印。
1)字节打印流:PrintStream
构造函数可以接收的参数类型:
file对象:File
字符串路径:String
字节输出流:OutputStream
2)字符打印流:PrintWriter
构造函数可以接收的参数类型:
file对象:File
字符串路径:String
字节输出流:OutputStream
字符输出流:Writer
- public static void main(String[] args) throws IOException{
- BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
- PrintWriter out = new PrintWriter(System.out,true);
- //PrintWriter out = new PrintWriter(new FileWriter("a.txt"),true);
- String line = null;
- while((line = bufr.readLine())!=null) {
- if("over".equals(line))
- break;
- out.println(line.toUpperCase());
- //out.flush();
- }
- out.close();
- bufr.close();
- }
9、SequenceInputStream
- public static void main(String[] args)throws IOException {
- Vector<FileInputStream> v = new Vector<FileInputStream>();
- v.add(new FileInputStream("d:\\test\\1.txt"));
- v.add(new FileInputStream("d:\\test\\2.txt"));
- v.add(new FileInputStream("d:\\test\\3.txt"));
- Enumeration<FileInputStream> en = v.elements();
- SequenceInputStream sis = new SequenceInputStream(en);
- FileOutputStream fos = new FileOutputStream("d:\\test\\4.txt");
- byte[] buf = new byte[1024];
- int len = 0 ;
- while((len=sis.read(buf))!=-1) {
- fos.write(buf,0,len);
- }
- fos.close();
- sis.close();
- }
10、切割文件
- public class SplitFileDemo {
- public static void main(String[] args) throws IOException{
- //splitFile();
- merge();
- }
- public static void merge() throws IOException{
- ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
- for (int x=1;x<=3;x++) {
- al.add(new FileInputStream("d:\\splitfiles"+x+".part"));
- }
- final Iterator<FileInputStream> it = al.iterator();
- Enumeration<FileInputStream> en = new Enumeration<FileInputStream>(){
- public boolean hasMoreElements() {
- return it.hasNext();
- }
- public FileInputStream nextElement() {
- return it.next();
- }
- };
- SequenceInputStream sis = new SequenceInputStream(en);
- FileOutputStream fos = new FileOutputStream("d:\\splitfiles\\0.jpg");
- byte[] buf = new byte[1024];
- int len = 0;
- while((len = sis.read(buf))!=-1) {
- fos.write(buf,0,len);
- }
- fos.close();
- sis.close();
- }
- public static void splitFile()throws IOException {
- FileInputStream fis = new FileInputStream("d:\\1.jpg");
- FileOutputStream fos = null;
- byte[] buf = new byte[1024*1024];
- int len = 0;
- int count = 0;
- while((len=fis.read(buf))!=-1) {
- fos = new FileOutputStream("d:\\splitfiles\\"+(count++)+".part");
- fos.write(buf,0,len);
- fos.close();
- }
- fis.close();
- }
- }
---------------------- ASP.Net+Android+IOS开发、 href="http://edu.csdn.net"target="blank">.Net培训、期待与您交流! ----------------------详细请查看: http://edu.csdn.net