十一.Java基础_File类

来源:互联网 发布:算法导论捷径 编辑:程序博客网 时间:2024/06/08 19:39

Java基础_File类

一.File类常见方法

1.创建

boolean createNewFile():在指定位置创建该文件,如果该文件已经存在,则不创建,返false;

和输出流不一样的地方:输出流对象建立后创建文件,而且文件已存在会覆盖文件;

boolean mkdir();创建文件夹

boolean makdirs();创建多级目录文件夹

2.删除

boolean delete();删除失败返回False

void deleteOnExit();在程序退出时删除文件

3.判断

boolean exists();文件是否存在

boolean canExecute():判断是否能执行

isFile();判断是否是文件

isDirectory()判断是否是目录

4.获取信息

getName();返回由此抽象路径名表示的文件或目录的名称。

getPath();获取相对路径

getAbsolutePath();获取绝对路径

getParent();返回绝对路径中的父目录,如果获取的是相对路径则返回null。例如:File f1  = new File("file.txt");则返回null,如果File f1 = new File("abc\\file.txt");则返回abc

.基本用法示例:

import java.io.*;class  Demo{public static void main(String[] args) throws IOException{//建立一个File对象File f1 = new File("file.txt");//methodcre(f1);//method_del(f1);//method_jud(f1);method_get(f1);}public static void methodcre(File f1) throws IOException{//创建文件,如果该文件已经存在,则不创建,返回false;show("creat:"+f1.createNewFile());//创建一个文件夹,如果该文件夹已经存在,则不创建,返回false;File dir = new File("abc");show("mkdir:"+dir.mkdir());//创建一个多级目录文件夹,如果该多级目录文件夹已经存在,则不创建,返回false;File dirs = new File("aaa\\bbb\\ccc\\ddd");show("mkdirs:"+dirs.mkdirs());}public static void method_del(File f1) throws IOException{//删除指定文件,删除失败返回Falseshow("delete:"+f1.delete());//在程序退出时删除文件,无返回值f1.deleteOnExit();}public static void method_jud(File f1) throws IOException{//判断文件是否存在,存在则返回trueshow(f1.exists());//判断应用程序是否可以执行此抽象路径名表示的文件。show(f1.canExecute());//判断是否是文件show(f1.isFile());//判断是否是目录show(f1.isDirectory());}public static void method_get(File f1) throws IOException{//返回由此抽象路径名表示的文件或目录的名称。show(f1.getName());//获取相对路径show(f1.getPath());//获取绝对路径show(f1.getAbsolutePath());/*返回绝对路径中的父目录,如果获取的是相对路径则返回null。例如:File f1 = new File("file.txt");则返回null,如果File f1 = new File("abc\\file.txt");则返回abc*/show(f1.getParent());}public static void show(Object obj){System.out.println(obj);}}

.过滤文件方法

练习:文件过滤

/*需求:将一个文件夹里所有的.zip格式文件名列出来*/import java.io.*;class Demo1 {public static void main(String[] args) {File files = new File("E:\\android\\java基础\\20tian");//这里使用内部类实现FilenameFileter接口里面的accept功能实现文件过滤String[] arr = files.list(new FilenameFilter(){public boolean accept(File files,String name){//只要文件名字里面包含".zip",就返回truereturn name.contains(".zip");}});//列出符合条件的文件名for (String name : arr ){System.out.println(name);}}}

四.递归调用

这里要实现一个方法:列出指定目录下的所有内容

首先要实现一个可以列出目录的功能,然后在列出内容的过程中如果出现的还是目录的话,可以再次调用本功能,也就是函数自身调用自身。

注意:1.递归条件的设置

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

练习:列出文件夹里所有的文件名

import java.io.*;class Demo {public static void main(String[] args) {File dir = new File("E:\\tian");showdir(dir,0);}public static void showdir(File dir,int level){System.out.println(getLevel(level)+dir);level++;File[] files = dir.listFiles();for (int x=0;x<files.length;x++){//如果该文件是目录,则再次调用showdir功能if(files[x].isDirectory())showdir(files[x],level);else System.out.println(files[x]);}}public static String getLevel(int level){StringBuilder sb = new StringBuilder();for (int x=0;x<level ;x++ ){sb.append("|--");}return sb.toString();}}

练习:复制文件夹

import java.io.*;class MainClass {public static void main(String[] args) throws Exception{//假设你把E盘下“aaa”这个文件夹给拷贝到E盘并命名为copyfilefindAndCopyPics("E:\\aaa","E:\\copyfile");}public static void findAndCopyPics(String fpath,String dpath) throws Exception {File file = new File(fpath);if (file.isDirectory()){File copyfile = new File(dpath);copyfile.mkdirs();}File[] listFiles = file.listFiles();for (File f : listFiles) {if (f.isDirectory()) {// 是文件夹就递归findAndCopyPics(fpath + "\\" + f.getName(),dpath+"\\"+f.getName());} else {// 不是文件夹,即是文件就拷备copyPics(fpath + "\\" + f.getName(),dpath+"\\"+f.getName());}}}public static void copyPics(String fpath,String dpath) throws Exception {FileInputStream fis = new FileInputStream(fpath);FileOutputStream fos = new FileOutputStream(dpath);byte[] b = new byte[1024];int len = 0;while ((len=fis.read(b))!=-1) {fos.write(b,0,len);}fis.close();fos.close();}}

.操作配置文件

Properties可以用来操作键值对形式的配置文件,是Hashtable的子类 ,里面存储的是键值对,键值对都是字符串。

下面用代码演示它的一系列用法:

  import java.io.*;  import java.util.*;  class Demo   {  public static void main(String[] args) throws IOException  {  method_2();  }  public static void method_2() throws IOException  {  Properties prop = new Properties();  FileInputStream fis = new FileInputStream("info.txt");  //将流中的数据加载进集合  prop.load(fis);  //修改或设置数据  prop.setProperty("dddd","39");  //获得键为"bbbb"所对应的值  System.out.println(prop.getProperty("bbbb"));    FileOutputStream fos = new FileOutputStream("info.txt");//调用写入流  prop.store(fos,"aaaaaaaaaaaaaaaa");//加入注释信息“aaa”  System.out.println(prop);//直接打印集合  prop.list(System.out);//列出集合目录  }  //下面是Properties类中load方法的原理  public static void method_1() throws IOException  {  BufferedReader bfr = new BufferedReader(new FileReader("info.txt"));    String line = null;  Properties prop = new Properties();  while ((line=bfr.readLine())!=null)  {  String[] arr = line.split("=");  prop.setProperty(arr[0],arr[1]);  }  bfr.close();  System.out.println(prop);  }  }

练习:利用配置文件,使一个程序运行超过3次就不能再运行

  import java.io.*;  import java.util.*;  class Demo1  {  public static void main(String[] args) throws IOException  {  File file = new File("infos.ini");  if (!file.exists())  {  file.createNewFile();  }  FileInputStream fis = new FileInputStream(file);  Properties prop = new Properties();  //将流中的数据加载进集合  prop.load(fis);    String value = prop.getProperty("time");  int count = 0;  //如果value值不为null,则判断count值是否大于3  if (value!=null)  {  count = Integer.parseInt(value);  if (count>=3)  {  System.out.println("已经运行三次了!");  //大于3则停止运行  return;  }  }  count++;  prop.setProperty("time",count+"");  FileOutputStream fos = new FileOutputStream(file);  //写入文件  prop.store(fos,count+"");  fis.close();  fos.close();  }}

.打印流

1PrintStream

PrintStream 为其他输出流添加了功能,使它们能够方便地打印各种数据值表示形式。与其他输出流不同,PrintStream 不会抛出 IOException

2PrintWriter

向文本输出流打印对象的格式化表示形式,与 PrintStream 类不同的是,如果启用了自动刷新,则只有在调用 printlnprintf 或 format 的其中一个方法时才可能完成此操作,而不是每当正好输出换行符时才完成。

代码实例:

/*打印流*/import java.io.*;class Demo {public static void main(String[] args) throws IOException{method_4();}public static void method_1() throws IOException{BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));PrintWriter out = new PrintWriter(System.out);//不加“true”,利用flush()刷新String line = null;while ((line=bfr.readLine())!=null){if ("over".equals(line)){break;}out.println(line.toUpperCase());out.flush();}out.close();bfr.close();}public static void method_2() throws IOException{BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));PrintWriter out = new PrintWriter(System.out,true);//加true配合下面的println自动刷新String line = null;while ((line=bfr.readLine())!=null){if ("over".equals(line)){break;}out.println(line.toUpperCase());//out.flush();}out.close();bfr.close();}public static void method_3() throws IOException{BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));//"true"自动刷新只对流操作,不能对文件使用,但是这样一来文件中的数据在写的过程当中也不能自动刷新了PrintWriter out = new PrintWriter("count.txt");String line = null;while ((line=bfr.readLine())!=null){if ("over".equals(line)){break;}out.println(line.toUpperCase());//out.flush();}out.close();bfr.close();}public static void method_4() throws IOException{BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));PrintWriter out = new PrintWriter(new FileWriter("count.txt"),true);//将count.txt文件放入流中,这时可用true自动刷新功能String line = null;while ((line=bfr.readLine())!=null){if ("over".equals(line)){break;}out.println(line.toUpperCase());//out.flush();}out.close();bfr.close();}}

.序列流

SequenceInputStream:对多个流进行合并

import java.io.*;import java.util.*;class Demo {public static void main(String[] args) throws IOException{Vector<FileInputStream> v = new Vector<FileInputStream>();v.add(new FileInputStream("1.txt"));v.add(new FileInputStream("2.txt"));v.add(new FileInputStream("3.txt"));Enumeration<FileInputStream> en= v.elements();///合并三个流SequenceInputStream sis = new SequenceInputStream(en);//将三个流里面的数据全写入一个流FileOutputStream fos = new FileOutputStream("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();}}

练习:

/*需求:编写一个可以切割和合并文件的功能*/import java.io.*;import java.util.*;class Demo {public static void main(String[] args) throws IOException{//split();hebing();}//切割文件public static void split() throws IOException{FileInputStream fis = new FileInputStream("50314.jpg");FileOutputStream fos = null;int len = 0;byte[] buf = new byte[1024*10];int count = 1;while ((len=fis.read(buf))!=-1){fos = new FileOutputStream((count++)+".part");fos.write(buf,0,len);fos.close();}fis.close();}//合并文件public static void hebing() throws IOException{ArrayList<FileInputStream> arr = new ArrayList<FileInputStream>();for (int x=1;x<=10;x++ ){arr.add(new FileInputStream(x+".part"));}final Iterator<FileInputStream> it = arr.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("hebing.jpg");int len = 0;byte[] buf = new byte[1024];while ((len = sis.read(buf))!=-1){fos.write(buf,0,len);}fos.close();sis.close();}}






0 0
原创粉丝点击