JAVA程序员11.ppt
JAVA程序员培训-11讲师:朱晓File类File类是IO包中唯一代表磁盘文件本身的对象,File类定义了一些与平台无关的方法来操纵文件,通过调用File类提供的各种方法,能够创建、删除、重命名文件,判断文件的读写权限及是否存在,设置和查询文件的最近修改时间。文件操作File类File类既可以操作文件,也可以操作目录创建File类对象File f;f=new File(Test.java);f=new File(E:ex,Test.java);在Java中,将目录也当作文件处理File类中提供了实现目录管理功能的方法File path=new File(E:ex);File f=new File(path,Test.java);File类方法介绍关于文件/目录名操作 String getName()String getPath()String getAbsolutePath()String getParent()boolean renameTo(File newName)File 测试操作 boolean exists()boolean canWrite()boolean canRead()boolean isFile()boolean isDirectory()boolean isAbsolute();获取常规文件信息操作 long lastModified()long length()boolean delete()目录操作 boolean mkdir()boolean mkdirs()String list()File listFiles()I/O数据流输入输出在java.io包中提供了对数据流输入输入的类可分为两组按字节为单位处理数据流的InputStream和OutputStream按字符为单位处理数据流的Reader和Writer它们都是抽象类,常用的子类有FileInputStream,ObjectInputStream,FileOutputStream,ObjectOutputStream,InputStreamReader,FileReader,BufferedReader,OutputStreamWriter,FileWriter,BufferedWriter文件I/O有关类型文件输入可使用FileReader类以字符为单位从文件中读入数据可使用BufferedReader类的readLine方法以行为单位读入一行字符文件输出可使用FileWriter类以字符为单位向文件中写出数据使用PrintWriter类的print和println方法以行为单位写出数据文件输入举例 import java.io.*;public class Test9_4 public static void main(String args)String fname=Test9_4.java;File f=new File(fname);try FileReader fr=new FileReader(f);BufferedReader br=new BufferedReader(fr);String s=br.readLine();while(s!=null)System.out.println(读入:+s);s=br.readLine();br.close();/关闭缓冲读入流及文件读入流的连接.catch(FileNotFoundException e1)System.err.println(File not found:+fname);catch(IOException e2)e2.printStackTrace();文件输出举例import java.io.*;public class Test9_5 public static void main(String args)File file=new File(tt.txt);try InputStreamReader is=new InputStreamReader(System.in);BufferedReader in=new BufferedReader(is);FileWriter fw=new FileWriter(file)PrintWriter out =new PrintWriter(fw);String s=in.readLine();while(!s.equals()/从键盘逐行读入数据输出到文件out.println(s);s=in.readLine();in.close();/关闭BufferedReader输入流.out.close();/关闭连接文件的PrintWriter输出流.catch(IOException e)System.out.println(e);I/O控制台(Console I/O)System.out 提供向“标准输出”写出数据的功能System.out为 PrintStream类型.System.in 提供从“标准输入”读入数据的功能System.in 为InputStream类型.System.err提供向“标准错误输出”写出数据的功能System.err为 PrintStream类型.向标准输出写出数据System.out/System.err的println/print方法println方法可将方法参数输出并换行 print方法将方法参数输出但不换行print和println方法针对多数数据类型进行了重写(boolean,char,int,long,float,double以及char,Object和 String).print(Object)和println(Object)方法中调用了参数的toString()方法,再将生成的字符串输出从标准输入读取数据import java.io.*;public class Test9_3 public static void main(String args)String s;/创建一个BufferedReader对象从键盘逐行读入数据InputStreamReader isr=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(isr);try/每读入一行后向显示器输出s=br.readLine();while(!s.equals()System.out.println(Read:+s);s=br.readLine();br.close();/关闭输入流 catch(IOException e)/捕获可能的IOException.e.printStackTrace();本章重点