---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------
这部分的内容主要有以下几个知识点:
1.File类;
2.Properties类;
3.IO体系的其他一些流;
一、File类
File类用来将文件或者文件夹封装成对象,方便对文件和文件夹的属性信息进行操作。同时,File对象可以作为参数传递给流的构造函数。
1.常用的三种构造函数
//File(String pathname);
File f1 = new File("a.txt");
//File(String parent, String child);
File f2 = new File("c:\\abc","b.txt");
//File(File parent, String child);
File d = new File("c:\\abc");
File f3 = new File(d,"c.txt");
2.File对象的常见方法
创建:
createNewFile():在指定位置创建文件,如果该文件已经存在,则不创建返回false。
mkdir():创建目录(文件夹)。
mkdirs():创建多级目录。
删除:
delete():删除文件或文件夹,如果删除的是文件夹,只有当文件夹为空时才可以删除成功。
deleteOnExite():当程序退出时删除指定文件或文件夹。
判断:
canExecute():判断是否可执行。
canRead():判断是否可读。
canWrite():判断是否可修改。
exists():判断文件是否存在。
isFile():判断是否是文件。
isDirectory():判断是否是目录(文件夹)。
isHidden():判断是否隐藏。
isAbsolute():判断是否是绝对路径。
获取信息:
getName():获取名称。
getParent():获取父目录,如果没有指定,返回null。
getPath():获取路径名。
getAbsolutePath():获取绝对路径名。
lastModified():获取最后一次修改的时间。
length():获取文件的长度。
其他:
renameTo(File dest):重命名文件。
list():列出目录下的所有文件和目录名。
list(FilenameFilter filter):列出满足过滤器的文件和目录。
listRoots():列出可用的文件系统根目录。
示例代码1
/*
File类
*/
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
//consMethod();
method_4();
}
//renameTo()
public static void method_4()
{
File f1 = new File("c:\\version.conf");
File f2 = new File("d:\\nimei.conf");
f2.renameTo(f1);
}
//获取信息
public static void method_3() throws IOException
{
File f = new File("nimei\\file.txt");
sop("path:"+f.getPath());//获取路径
sop("abspath:"+f.getAbsolutePath());//获取绝对路径
sop("parent:"+f.getParent());//只有当封装的是多级目录时才有返回值,否则返回null
sop("lastModified:"+f.lastModified());
sop("length:"+f.length());
}
//判断
public static void method_2() throws IOException
{
File f = new File("file.txt");
sop(f.mkdir());
//sop(f.createNewFile());
sop("canExecute:"+f.canExecute());
sop("canRead:"+f.canRead());
sop("canWrite:"+f.canWrite());
sop("exists:"+f.exists());
sop("isAbsolute:"+f.isAbsolute());//只判断给的路径,不必文件或目录存在
//在判断文件对象是否是文件或目录时,必须先通过exists()判断该文件对象封装的内容是否存在
sop("isFile:"+f.isFile());//判断是否是文件
sop("isDirectory:"+f.isDirectory());//判断是否是目录
sop("isHidden:"+f.isHidden());//判断是否是隐藏的文件
}
//创建和删除
public static void method_1() throws IOException
{
File f = new File("aaa\\bbb\\ccc\\ddd\\eee\\fff");
//f.deleteOnExit();//当程序退出时删除指定文件
//如果创建成功返回true,如果需要创建的文件已经存在则创建失败,这点与流不同
//sop("create:"+f.createNewFile());
//sop("delete:"+f.delete());//删除文件或文件夹,如果是文件夹只有当期为空的时候才可以删除,否则删除失败
//sop("mkdir:"+f.mkdir());//创建目录(文件夹),只能已存在的目录下创建一级目录
sop("mkdirs:"+f.mkdirs());//创建多级目录
}
//创建File对象,可以将已有的和未出现的文件或者文件夹封装成对象
public static void consMethod()
{
//File(String pathname);
File f1 = new File("a.txt");
//File(String parent, String child);
File f2 = new File("c:\\abc","b.txt");
//File(File parent, String child);
File d = new File("c:\\abc");
File f3 = new File(d,"c.txt");
//跨平台的目录分隔符,File.separator
File f4 = new File("c:"+File.separator+"aaa"+File.separator+"bbb"+
File.separator+"d.txt");
sop("f1:"+f1);
sop("f2:"+f2);
sop("f3:"+f3);
sop("f4:"+f4);
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
import java.io.*;
class FileDemo2
{
public static void main(String[] args)
{
//listRootsDemo();
listFilterNameDemo();
}
//File对象的list(FilenameFilter filter)方法
//只打印.java文件
public static void listFilterNameDemo()
{
File f = new File("d:\\bxdjavademo");
String[] names = f.list(new FilenameFilter(){
public boolean accept(File dir,String name){
//System.out.println(dir);
//System.out.println(name);
/*
if(name.endsWith(".mkv"))
return true;
return false;
*/
return name.endsWith(".java");
}
});
for(String name:names)
System.out.println(name);
}
//File对象的list()方法
public static void listDemo()
{
File f = new File("c:\\");//使用list方法的File对象必须是目录,该目录还必须存在
String[] names = f.list();
//会打印c盘下所有的文件和目录,包括隐藏的
for(String name:names)
{
System.out.println(name);
}
}
//File类的listRoots()方法
public static void listRootsDemo()
{
File[] files = File.listRoots();
for(File f:files)
{
System.out.println(f);
}
}
}
3.列出目录下的所有内容-递归
需求:列出指定目录下的文件和文件夹,包含子目录中的内容。
分析:因为目录中还有目录,只要使用同一个列出目录功能的函数完成即可。在列出过程中出现的还是目录的话,可以再次调用本功能,也就是函数自身调用自身。这种表现形式或编程手法,成为递归。
递归要注意:限定条件;注意递归的次数,避免内存溢出。
/*
列出指定目录下的所有内容,包括文件和文件夹以及文件夹中的内容
*/
import java.io.*;
class FileDemo3
{
public static void main(String[] args)
{
File dir = new File("D:\\testdir");
showDir(dir);
//toBin(6);
//System.out.println("\r\nsum:"+getSum(9000));//注意递归次数,避免内存溢出
}
public static void showDir(File dir)
{
/*
如果是第一级目录则打印整个绝对路径,
否则只打印文件或者文件夹的名字
*/
System.out.println(dir);;
File[] files = dir.listFiles();
for(File file:files)
{
if(file.isDirectory())
showDir(file);
else
System.out.println(file);
}
}
//使用递归的方法获取从1到num的连续整数的和
public static int getSum(int num)
{
if(num==1)
return 1;
else
return num+getSum(num-1);
}
//用递归的方法打印一个正整数的二进制形式
public static void toBin(int num)
{
if(num>0)
{
toBin(num/2);
System.out.print(num%2);
}
}
}
/*
列出指定目录下的所有内容,带层次
*/
import java.io.*;
class FileDemo4
{
public static void main(String[] args)
{
File dir = new File("D:\\testdir");
showDir(dir,0);
}
public static String getLevel(int level)
{
StringBuilder sb = new StringBuilder();
sb.append("|--");
for(int x=0;x
4.删除带内容的目录
原理,在windows中,删除目录是从里往外删除的,所以就需要用到递归。
/*
删除带内容的目录
*/
import java.io.*;
class RemoveDirDemo
{
public static void main(String[] args)
{
File dir = new File("d:\\testdir");
deleteFile(dir);
}
public static void deleteFile(File dir)
{
File[] files = dir.listFiles();
for(File file : files)
{
if(file.isDirectory())//判断是否是目录,如果是,递归执行函数
deleteFile(file);
else
{
//删除文件,打印删除结果
String r = file.delete()?" success":" fail";
sop("delete file "+file+r);
}
}
//删除目录,打印删除结果
String rs = dir.delete()?" success":" fail";
sop("delete dir "+dir+rs);
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
5.创建Java文件列表
将一个目录下的所有java文件的绝对路径,存储到一个文本文件中。
思路:
(1)对指定的目录进行递归;
(2)获取递归过程中所有的java文件;
(3)将这些文件对象存储到集合中;
(4)将集合中的数据写入到一个文件中。
/*
将一个指定目录下的java文件的绝对路径存储到一个文本文件中,
建立一个java文件列表
*/
import java.io.*;
import java.util.*;
class JavaListFileDemo
{
public static void main(String[] args)
{
File dir = new File("d:\\bxdjavademo");
List
list = new ArrayList
();
fileToList(dir,list);
//System.out.println(list.size());
File file = new File(dir,"javalist.txt");
writeToFile(file,list);
}
//将所有java文件的File对象存储到集合中
public static void fileToList(File dir, List
list)
{
File[] files = dir.listFiles();
for(File file : files)
{
if(file.isDirectory())
fileToList(file,list);
else
if(file.getName().endsWith(".java"))
list.add(file);
}
}
//将集合中File对象对应文件的绝对路径写入到文件中
public static void writeToFile(File file,List
list)
{
BufferedWriter bufw = null;
try
{
bufw = new BufferedWriter(new FileWriter(file));
for(File f:list)
{
String abspath = f.getAbsolutePath();
bufw.write(abspath);
bufw.newLine();
bufw.flush();
}
}
catch (IOException e)
{
/*
如果throw e,则必须在该方法后面加上throws IOException
如果throw new RuntimeException()则不用
*/
throw new RuntimeException("写入失败");
}
finally
{
if(bufw!=null)
try
{
bufw.close();
}
catch (IOException e)
{
throw new RuntimeException("关闭失败");
}
}
}
}
二、Properties对象及其应用
Properties是hashtable的子类,具备map集合的特点,存储的键值对都是字符串。是集合中和IO技术相结合的容器。该对象可以用于键值对形式的配置文件。在加载数据时,需要有固定格式,键=值。
1.Properties对象
/*
Properties对象
*/
import java.util.*;
import java.io.*;
class PropertiesDemo
{
public static void main(String[] args)
{
//setAndGet();
//method_1();
loadDemo();
}
public static void loadDemo()
{
Properties prop = new Properties();
FileInputStream fis = null;
FileOutputStream fos = null;
try
{
fis = new FileInputStream("info.txt");
prop.load(fis);//从输入流中读取属性列表
prop.setProperty("wangwu","25");
fos = new FileOutputStream("info.txt");
prop.store(fos,"nimei,wocao");//将Properties中的属性列表写出到输出流
}
catch (IOException e)
{
throw new RuntimeException("出现异常");
}
finally
{
if(fis!=null)
try
{
fis.close();
}
catch (IOException e)
{
throw new RuntimeException("读取流关闭异常");
}
if(fos!=null)
try
{
fos.close();
}
catch (IOException e)
{
throw new RuntimeException("写入流关闭异常");
}
}
//System.out.println(prop);
prop.list(System.out);
}
//将流中的数据存储到集合中
public static void method_1()
{
Properties prop = new Properties();
BufferedReader bufw = null;
try
{
bufw = new BufferedReader(new FileReader("info.txt"));
String line = null;
while((line=bufw.readLine())!=null)
{
String[] arr = line.split("=");
prop.setProperty(arr[0],arr[1]);
}
}
catch (IOException e)
{
throw new RuntimeException("读取文件异常");
}
finally
{
if(bufw!=null)
try
{
bufw.close();
}
catch (IOException e)
{
throw new RuntimeException("关闭异常");
}
}
System.out.println(prop);
}
//设置和获取
public static void setAndGet()
{
Properties prop = new Properties();
prop.setProperty("zhangsan","39");
prop.setProperty("lisi","38");
//System.out.println(prop);
Set
names = prop.stringPropertyNames();
for(String name:names)
System.out.println(name+":"+prop.getProperty(name));
}
}
2.记录应用程序的启动次数,如果达到使用次数限制则给出提示
建立一个配置文件,用于记录程序的启动次数。配置文件使用键值对的形式,便于阅读和操作数据。配置文件可以实现应用程序数据的共享。
/*
将应用程序的启动次数写入配置文件中,
达到限制次数后,给出注册提示
*/
import java.io.*;
import java.util.*;
class RunCountDemo
{
public static void main(String[] args)
{
Properties prop = new Properties();
File f = new File("count.ini");
FileInputStream fis = null;
FileOutputStream fos = null;
try
{
if(!f.exists())
f.createNewFile();
fis = new FileInputStream(f);
prop.load(fis);
int count = 0;
String times = prop.getProperty("times");
if(times!=null)
{
count = Integer.parseInt(times);
if(count>=5)
{
System.out.println("您好,使用次数已到,请付钱");
return;
}
}
count++;
prop.setProperty("times",count+"");
fos = new FileOutputStream(f);
prop.store(fos,null);
}
catch (IOException e)
{
throw new RuntimeException("流异常");
}
finally
{
if(fis!=null)
try
{
fis.close();
}
catch (IOException e)
{
throw new RuntimeException("读取流关闭异常");
}
if(fos!=null)
try
{
fos.close();
}
catch (IOException e)
{
throw new RuntimeException("写入流关闭异常");
}
}
}
}
三、IO体系的一些其他流
1.PrintStream和PrintWriter
PrintStream构造函数可接收的参数类型:File对象;字符串路径String;字节输出流OutputStream。
PrintWriter构造函数可接收的参数类型:File对象;字符串路径String;字节输出流OutputStream;字符输出流Writer。
import java.io.*;
class PrintWriterDemo
{
public static void main(String[] args) throws IOException
{
BufferedReader bufw = new BufferedReader(new InputStreamReader(System.in));
//自动刷新,只有在调用 println、printf 或 format 的其中一个方法时才可以
PrintWriter pw = new PrintWriter(new FileWriter("a.txt"),true);
String line = null;
while((line=bufw.readLine())!=null)
{
if("over".equals(line))
break;
pw.println(line.toUpperCase());
//pw.flush();
}
bufw.close();
pw.close();
}
}
2.序列流SequenceInputStream
import java.io.*;
import java.util.*;
class SequenceInputStreamDemo
{
public static void main(String[] args) throws IOException
{
Vector
v = new Vector
();
v.add(new FileInputStream("c:\\1.mp3"));
v.add(new FileInputStream("c:\\2.mp3"));
v.add(new FileInputStream("c:\\3.mp3"));
Enumeration
en = v.elements();
BufferedInputStream bufis = new BufferedInputStream(new SequenceInputStream(en));
BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("c:\\4.mp3"));
byte[] buf = new byte[1024];
int len = 0;
while((len = bufis.read(buf))!=-1)
{
bufos.write(buf,0,len);
}
bufis.close();
bufos.close();
}
}
3.切割文件
import java.io.*;
import java.util.*;
class SplitFileDemo
{
public static void main(String[] args) throws IOException
{
//splitFile();
merge();
}
//合并文件
public static void merge() throws IOException
{
ArrayList
list = new ArrayList
();
for(int x=1;x<=4;x++)
{
list.add(new FileInputStream("splitfiles\\"+x+".part"));
}
final Iterator
it = list.iterator();
Enumeration
en = new Enumeration
(){ public boolean hasMoreElements() { return it.hasNext(); } public FileInputStream nextElement() { return it.next(); } }; SequenceInputStream sis = new SequenceInputStream(en); FileOutputStream fos = new FileOutputStream("splitfiles\\lala.jpg"); byte[] buf = new byte[1024]; int len = 0; while((len=sis.read(buf))!=-1) fos.write(buf,0,len); sis.close(); fos.close(); } //切割文件 public static void splitFile() throws IOException { FileInputStream fis = new FileInputStream("aaa.jpg"); FileOutputStream fos = null; byte[] buf = new byte[1024*1024]; int len = 0; int index = 1; while((len=fis.read(buf))!=-1) { fos = new FileOutputStream("splitfiles\\"+(index++)+".part"); fos.write(buf,0,len); fos.close(); } fis.close(); } }
---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------
详细请查看:http://edu.csdn.net