详谈JAVA中的file类与IO流

2022-11-13,,,

File类
位置于java.io
构造方法:
File(String parent, String child)
new file(“d:\\”,”a.txt”)

File(String pathname)
new file(“d:\\a.txt”)

File(File parent, String child)
File f = new File(“d:\\”);
File f1=new File(f,”a.txt”)

常用方法:
1.获取
1)文件名
String getName()
2)文件路径
String getAbsolutePath()
3)大小
long length()
3)最后个修改时间
long lastModified()

File file = new File("d:\\aa.txt");
System.out.println(file.getName());
System.out.println(file.getAbsolutePath());
System.out.println(file.lastModified());
long l = file.lastModified();
Date date= new Date(l);
System.out.println(date.toString());
System.out.println(file.length());
2.创建与删除
1)创建文件
boolean createNewFile()
2)创建文件夹(目录)
boolean mkdir() 单层
boolean mkdirs() 多层
3)删除文件和目录
boolean delete()

File f= new File("d:\\b.txt");
boolean b = f.createNewFile();
System.out.println(b);
f.delete();

File f1= new File("d:\\ch1027");
f1.mkdir();
File f2= new File("d:\\ch1028\\ch1029\\ch1030");
f2.mkdirs();

File f2= new File("d:\\ch1028\\ch1029\\ch1030");
System.out.println(f2.delete());
3.判断
boolean isDirectory() 测试此抽象路径名表示的文件是否是一个目录。
boolean isFile() 测试此抽象路径名表示的文件是否是一个标准文件。
boolean isHidden() 测试此抽象路径名指定的文件是否是一个隐藏文件。

File f1=new File("d:\\ch1027");
System.out.println(f1.isDirectory());
System.out.println(f1.isFile());

File f= new File("d:\\bb.txt");
boolean b = f.createNewFile();
System.out.println(f.isHidden());
4.重命名
boolean renameTo(File dest)
1)同目录 ---- 改名
2)不同目录 ----- 相当于剪切

File f= new File("f:\\bb6.txt");
File f1= new File("f:\\123\\bb6.txt");
System.out.println(f.renameTo(f1));
5.其它
static File[] listRoots() 列出可用的文件系统根。
long getFreeSpace() 可用空间
long getTotalSpace() 总容量
String[] list() 列出目录中的文件和目录(同辈目录)
File[] files = File.listRoots();
for(int i=0;i<files.length;i++){
System.out.println(files[i]);
}

File f= new File("f:\\");
System.out.println(f.getFreeSpace());
System.out.println(f.getTotalSpace());

File f= new File("f:\\123");
String [] strs = f.list();
for(int i=0;i<strs.length;i++){
System.out.println(strs[i]);
}
FileFilter接口 
文件过滤器
例子:显示出某个目录下的,非隐藏文件
File[] listFiles(FileFilter filter)
参数是一个过滤器类
详见下面程序

public class FilteHidden implements FileFilter{
public boolean accept(File file) {
return !file.isHidden();
}
}
public class Filess {
public static void main(String[] args) {
File file = new File("f:\\123");
File [] s = file.listFiles(new FilteHidden());
for(int i=0;i<s.length;i++){
System.out.println(s[i].getName());
}
}
}

FilenameFilter 接口
文件名过滤器
例子:对文件名进行过滤
File[] listFiles(FilenameFilter filter)
参数是一个过滤器类
详见下面程序

public class Filename implements FilenameFilter{
private String endstr;
public boolean accept(File dir, String name) {
return name.endsWith(endstr);
}
Filename(String str){
endstr = str;
}
}
public class FilenameDemo {
public static void main(String[] args) {
File file= new File("f:\\123");
File [] files = file.listFiles(new Filename(".txt"));
for(int i=0;i<files.length;i++){
System.out.println(files[i].getName());
}
}
}

File类 得到文件列表的方法
1)列出所有文件
File file = new File(“f:\\aa”);
File [] filearr = file.listFiles(); 表示的目录中的(文件及目录)
String [] filearr= file.list(); 表示的目录中的(文件及目录)
2)过滤器
File file = new File(“f:\\aa”);
FilenameFilter接口,用于过滤文件名。
String[] filenamearr= file.list(FilenameFilter filter)
File[] filenamearr = file.listFiles(FilenameFilter filter)

File file = new File(“f:\\aa”);
FileFilter接口,用于过滤文件。
File[] filearr = file.listFiles(FileFilter filter)

递归:自已(方法)调用自已
例子:用递归把目录下所有的目录及文件全部显示出来
public class B {
public static void main(String[] args) {
File file = new File("f:\\123");
listAllFile(file);
}
public static void listAllFile(File file) {
File[] strs = file.listFiles();
for (int i = 0; i < strs.length; i++) {
// 是不是目录strs[i]
if (strs[i].isDirectory()) {
listAllFile(strs[i]);
System.out.println("目录="+strs[i].getName());
} else {
System.out.println("文件名="+strs[i].getName());
}
}
}
}

IO流
IO流:输入(Input)输出(Output)流
位置于java.io包下
流作用:读取文件用的
流分类
1)按流向分(以内存为参照物):
输入流 输出流
2)按流的内容分:
字节流(能读写所有文件),字符流(读取纯文本文件)
3)按功能分:
节点流 处理流(套在节点流上的)
字节流,它的子类都是Stream
字符流,它的子类是Writer Reader
FileWriter
文件字符输出流
构造方法:
注意:1)对象一创建出来就得给文件路径。
2)如果文件存在就覆盖,不存在则创建
3)不想覆盖,是用
FileWriter(String fileName, true)
4)写完后要flush()
5)写完要关闭流
FileReader
文件字符输入流
代码:
1)
FileWriter fw = new FileWriter("d:\\1.txt");//文件有覆盖,没有则创建
fw.write("abc");
fw.flush();
fw.close(); 关闭后不能在写入
2)
public static void main(String[] args) {
try {
FileReader fr = new FileReader("f:\\1.txt");
int ch=0;
while( (ch=fr.read())!=-1 ){ 读到最后返回值为-1
System.out.println((char)ch);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
3)
public static void main(String[] args) {
try {
FileReader fr = new FileReader("f:\\1.txt");
char[] buf= new char[3];
int i = fr.read(buf);
System.out.println(new String(buf,0,i));
//new String(buf,0,i) char [] buf,从char数组的第几个位置开始读,读几个
int i1 = fr.read(buf);
System.out.println(new String(buf,0,i1));
} catch (Exception e) {
e.printStackTrace();
}
}
4)
public class FileWriterDemo {
public static void main(String[] args) {
FileWriter fw = null;
try {
fw = new FileWriter("d:\\1.txt");
fw.write("fff");
fw.write("ggggg");
fw.flush();
int i = 10/0;
} catch (Exception e) {
String str = e.getMessage();
FileWriterDemo d = new FileWriterDemo();
d.xie(str);错误信息写入另一个文件中。
e.printStackTrace();
} finally {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void xie(String str) {
FileWriter fw = null;
try {
fw = new FileWriter("d:\\2.txt", true);
fw.write(str);
fw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BufferedWriter 带缓冲区的文件字符输出流
特点:1)它是处理流,要包在节点流外面来使用
2)提高写的效率
3)换行newLine()
创建对象:
1)FileWriter fw = new FileWriter("d:\\cc\\cc.txt");
BufferedWriter bw = new BufferedWriter(fw);
2)没有捕获异常时
BufferedWriter bw1 = new BufferedWriter(new FileWriter("d:\\cc\\cc3.txt"));
bw1.write("abcbbbb");
bw1.newLine();
bw1.write("sssss");
bw1.newLine();
bw1.write("defxxx");
bw1.flush();
bw1.close();
BufferedReader 带缓冲区的文件字符输入流
特点:1)它是处理流,要包在节点流外面来使用
2)提高读取的效率
3)读一行readLine()
创建对象:
try {
BufferedReader br= new BufferedReader(new FileReader("d:\\cc\\cc.txt"));
String str=null;
while( (str=br.readLine()) != null){
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
}
文件的复制:
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(new File("d:\\cc\\cc.txt")));
bw = new BufferedWriter(new FileWriter("d:\\cc\\cc5.txt"));
String str = null;
while ((str = br.readLine()) != null) {
bw.write(str);
bw.newLine();
bw.flush();
}

} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}

}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

FileOutputStream 文件字节输出流
特点:1)输出的是字节
2)不用flush()
创建对象:
public static void main(String[] args) {
FileOutputStream fos=null;
try{
fos = new FileOutputStream("d:\\cc\\cc8.txt");
fos.write("abc".getBytes());
//getBytes()将一个字符串转化为一个字节数组byte[]的方法
fos.write(97);
}catch (Exception e) {
e.printStackTrace();
}finally{
if(fos != null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

FileInputStream 文件字节输入流
特点:1)输入的是字节
2)不用flush()
创建对象:
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("d:\\cc\\cc8.txt");
byte [] b = new byte[2];
int len=0;
while( (len =fis.read(b)) != -1){
System.out.println(new String(b,0,len));
}
} catch (Exception e) {
e.printStackTrace();
}
}

BufferedOutputStream BufferedInputStream
带缓冲区的字节输出(输入)流
特点:1)输出(入)的是字节
2)是个处理流
2)用flush()

创建对象:
public static void main(String[] args) {
try {
BufferedInputStream bis= new BufferedInputStream( new FileInputStream("d:\\cc\\cc8.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:\\cc\\cc9.txt"));
int len=0;
byte [] b = new byte[1024];
while( (len = bis.read(b)) !=-1 ){
bos.write(b);
}
bos.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{//加close()方法,请参考(文件的复制)}
}

System.in
从键盘输入得到一个流InputStream
用InputStream中的方法
public static void main(String[] args) {
InputStream is = System.in;
int ch = 0;
try {
while ((ch = is.read()) != -1) {
System.out.println((char) ch); // \r 13 \n 10
}
} catch (IOException e) {
e.printStackTrace();
}
}

ObjectInputStream ObjectOutputStream
对象的输入 输出流
特点:1)写入很多数据类型
2)写入自定义对象
序列化:把对象存入硬盘中(属性的值)
反序列化:把对象从硬盘中取出来(属性的值)
注意: 1)static 修饰的属性不能存入
2)Transient修饰的属性不能存入//transient关键字的作用:标记的成员变量不参与序列化过程
3)对象对应的类必须要实现一个接口(空接口)Serializable接口
4)不用flush()
5)类中的方法不能被序列化,只能序列化属性
程序演示:
public static void main(String[] args) {
try {
ObjectOutputStream ous = new ObjectOutputStream(new FileOutputStream(new File("d:\\cc\\Animal.obj")));
Animal a1= new Animal("aa",1);
ous.writeObject(a1);//序列化
ous.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("d:\\cc\\Animal.obj")));
Animal an=(Animal)ois.readObject();//反序列化
System.out.println(an.getAge()+","+an.getName());
Ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}

详谈JAVA中的file类与IO流的相关教程结束。

《详谈JAVA中的file类与IO流.doc》

下载本文的Word格式文档,以方便收藏与打印。