第十三章 I/O流

来源:互联网 发布:天涯明月刀数据异常 编辑:程序博客网 时间:2024/05/20 03:39
File类
   File对象包含了文件中的所有字节数据,以及文件的其他详细信息。
   创建File对象
  1. //File对象包含了文件中的所有字节数据,以及文件的其他详细信息
  2. File file;
  3. //使用绝对路径创建文件
  4. file = new File("d:/myFile/a/test.txt");
  5. //通过父文件对象创建
  6. file = new File(new File("d:/myFile"), "a/test.txt");
  7. file = new File(new File("d:/myFile/a"),"test.txt");
  8. //通过父文件路径创建
  9. file = new File("d:/myFile", "a/test.txt");

常见的File的操作
    创建、重命名、删除、复制、剪切、黏贴

File对象的方法
    exists    判断文件是否已经存在
    getAbsolutePath   获取文件的绝对路径
    isFile 是否是单个的文件
    isDirectory  是否是文件夹
    listFiles     获取文件夹中的子文件
    createNewFile    创建新文件
    mkdir       创建文件夹
    delete      删除
    renameTo    重命名


获取文件的文件名
  1. file.getName();
获取文件的父文件路径
  1. file.getParent();
获取文件的长度(字节数)
  1. file.length();
获取文件所在盘符的剩余字节大小
  1. file.getFreeSpace();
获取文件所在盘符的总大小
  1. file.getTotalSpace();
获取文件所在盘符的可用空间
  1. file.getUsableSpace();
是否是可执行文件
  1. file.canExecute()
是否可读
  1. file.canRead();
是否可写
  1. file.canWrite();
文件最后一次修改的时间
  1. file.lastModified();
  2. //返回long型
  3. long time = file.lastModified();
  4. Date date = new Date(time);
是否是隐藏文件
  1. file.isHidden();
获取文件中的子文件
  1. File[] files = file.listFile();
获取当前操作系统的所有盘符
  1. File[] disks = File.listRoots();

删除文件
    可以用于文件和文件夹,如果是文件夹,并且该文件夹有子文件,则不能删除,要删除必须清空文件夹的子文件
  1. file.delete()


操作
查看所有文件的方法
  1. /**
  2. * 查看所有文件的方法
  3. */
  4. public void showFiles(String path){
  5. //根据路径获得文件
  6. File file = new File(path);
  7. //判断文件是否存在
  8. if(file.exists()){
  9. System.out.println(file.getAbsolutePath());
  10. //判断是否是文件夹
  11. if(file.isDirectory()){
  12.    //如果是文件夹,则获取文件夹中的子文件
  13.    File[] files = file.listFiles();
  14.    if(files != null){
  15.    //遍历子文件
  16.    for(File childFile : files){
  17.    //递归查看
  18.    showFiles(childFile.getAbsolutePath());
  19.    }    
  20.    }
  21. }
  22. }
  23. }

根据文件类型查找显示文件
  1. /**
  2. * 根据文件类型查找显示文件
  3. * @param path
  4. * @param type
  5. */
  6. public void showFiles(String path, String type){
  7. //根据路径获得文件
  8. File file = new File(path);
  9. //判断文件是否存在
  10. if(file.exists()){
  11. //判断文件是否是文件
  12. if(file.isFile()){
  13. //如果是文件就要判断文件的后缀名是否和查找的文件类型匹配
  14. if(validateFile(file.getName())){
  15. //获取文件的后缀名
  16. String fileType = file.getName().substring(file.getName().lastIndexOf(".")+1);
  17. //判断后缀名是否和查找文件匹配
  18. if(fileType.equalsIgnoreCase(type)){
  19. //打印显示文件
  20. System.out.println(file.getAbsolutePath());
  21. }
  22. }
  23. }
  24. //如果是文件夹递归查找
  25. else{
  26. //如果是文件夹,则获取文件夹中的子文件
  27. File[] files = file.listFiles();
  28. if(files != null){
  29. //遍历子文件
  30. for(File childFile : files){
  31. //递归查看
  32. showFiles(childFile.getAbsolutePath(),type);
  33. }
  34. }
  35. }
  36. }
  37. }
  38. /**
  39. * 验证文件是否是一个合法文件
  40. * @return
  41. */
  42. public boolean validateFile(String fileName){
  43. if(fileName.indexOf(".") != -1){
  44. return true;
  45. }
  46. return false;
  47. }

创建单个文件的方法
  1. /**
  2. * 创建单个文件的方法
  3. * @param fileName 新建的文件名
  4. * @param path 创建的位置
  5. */
  6. public void createFile(String fileName, String path){
  7. //根据父文件路径创建File对象
  8. File parentFile = new File(path);
  9. //判断父文件是否存在
  10. if(parentFile.exists()){
  11. //判断父文件是否是文件夹
  12. if(parentFile.isDirectory()){
  13. //构建File对象
  14. File file = new File(path, fileName);
  15. //判断要新建的文件是否存在
  16. if(!file.exists()){
  17. //创建
  18. try {
  19. file.createNewFile();
  20. } catch (IOException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24. }
  25. else{
  26. JOptionPane.showMessageDialog(null, "该文件已经存在!");
  27. }
  28. }
  29. }
  30. else{
  31. JOptionPane.showMessageDialog(null, "文件夹不存在!");
  32. }
  33. }

创建文件夹的方法
  1. /**
  2. * 创建文件夹的方法
  3. */
  4. public void createDirectory(String fileName, String path){
  5. //new File("").mkdir();
  6. }
  7. /**
  8. * 对文件进行重命名的方法
  9. * @param source 要修改的源文件路径
  10. * @param fileName 文件的新命名(不包含后缀名)
  11. */
  12. public void reNameFile(String source, String fileName){
  13. File sourceFile = new File(source);
  14. //判断源文件是否存在
  15. if(sourceFile.exists()){
  16. //判断源文件是否有后缀名
  17. if(validateFile(sourceFile.getName())){
  18. //获取源文件的后缀名
  19. String type = sourceFile.getName().substring(sourceFile.getName().lastIndexOf("."));
  20. //根据源文件的路径以及后缀名创建新命名的文件对象
  21. File file = new File(sourceFile.getParent(),fileName+type);
  22. ////判断新的文件名是否存在
  23. if(!file.exists()){
  24. //重命名
  25. sourceFile.renameTo(file);
  26. }
  27. }
  28. }
  29. }

删除文件的方法
  1. /**
  2. * 删除文件的方法
  3. */
  4. public void deleteFile(String path){
  5. File file = new File(path);
  6. ////删除文件,可以用于文件和文件夹
  7. ////如果是文件夹,并且该文件夹中有子文件,则不能删除
  8. ////如有以上情况则必须清空文件夹中的子文件
  9. //file.delete();
  10. //判断文件是否存在
  11. if(file.exists()){
  12. //判断文件是否是文件夹
  13. if(file.isDirectory()){
  14. //如果是文件夹获取子文件
  15. File[] files = file.listFiles();
  16. if(files != null){
  17. //递归删除
  18. for(File childFile : files){
  19. deleteFile(childFile.getAbsolutePath());
  20. }
  21. }
  22. }
  23. //无论是否是文件夹都应删除当前文件
  24. file.delete();
  25. }
  26. }



IO流
    InputStream           所有输入流的基类    是一个抽象类
    OutputStream           所有输出流的基类    也是一个抽象类
    常用的实现类
        FileInputStream                    FileOutputStream
        BufferedInputStream            BufferedOutputStream
   需要通过抽象的实例类才能对文件进行流的读写

读写
   通过输入流的read方法读取文件流的字节信息
   将每次读取到的信息通过输出流写入到新的文件中
  1. int data;
  2. while((data = input.read()) != -1){
  3. output.write(data);
  4. }

JAVA中IO流的分类
1、字节流
        以单字节的方式进行读取
2、字符流
        以单字符的方式进行读取

字符流在读取文本信息时效率高于字节流
字符流由字节流衍生而来,因此必须借助于字节流实现
字符流不能对单字节构成的文件进行读写,如视频图片

字符流
       Reader 字符输入流的基类    抽象类
       Writer    字符输出类的基类    抽象类
        InputStreamReader             OutputStreamWriter
        BufferedReader                    BufferedWriter   



1、使用字节流读写文件中的字节数据
  1. //数据流不能对文件夹进行读写
  2. FileInputStream fis = new FileInputStream(new File("d:/a.txt"));
  3. //每次读取一个字节,因此通过循环反复读取字节
  4. int data;
  5. while((data = fis.read()) != -1){
  6. system.out.println(data);
  7. }
  8. fis.close();

2、使用输出流将字节数据写入文件
  1. //创建输出流的时候如果文件不存在,则会自动创建文件,如果文件存在则将默认覆盖文件
  2. //第二个参数表示是否追加数据,默认为false
  3. FileOutputStream fos = new FileOutputStream(new File("d:/b.txt"),true);
  4. //写入数据
  5. fos.write(66);
  6. fos.write(67);
  7. //清空缓冲流
  8. fos.flush();
  9. fos.close();

(优)3、使用缓冲流优化
  1. BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("d:/flash.exe")));
  2. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("d:/test.exe")));
  3. int len;
  4. byte[] buffer = new byte[1024];
  5. while((len = bis.read(buffer)) != -1){
  6. bos.write(buffer, 0, len);
  7. }
  8. bis.close();
  9. bos.flush();
  10. bos.close();

(优)4、自定义缓冲流
  1. FileInputStream fis = new FileInputStream(new File("d:/flash.exe"));
  2. FileOutputStream fos = new FileOutputStream(new File("d:/test.exe"));
  3. //读取长度
  4. int len;
  5. //缓冲数组
  6. byte[] buffer = new byte[1024];
  7. //每次读取都将字节写入缓冲区
  8. while((len = fis.read(buffer)) != -1){
  9. //将缓冲区中的数据写入文件
  10. fos.write(buffer,0,len);
  11. }
  12. fis.close();
  13. fos.flush();
  14. fos.close();


字符流
字符流只适合读取纯文本的File文件,字符流的构建依赖于字节流

使用字符流读写文本
  1. try {
  2. InputStreamReader reader = new InputStreamReader(new FileInputStream(new File("d:/a.txt")));
  3. char[] buffer = new char[1024];
  4. StringBuffer str = new StringBuffer();
  5. int len;
  6. while((len = reader.read(buffer)) != -1){
  7. str.append(buffer);
  8. }
  9. reader.close();
  10. System.out.println(str);
  11. } catch (FileNotFoundException e) {
  12. e.printStackTrace();
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }

使用字符缓冲流
        InputStreamReader是字节流到字符缓冲流的桥梁
  1. try {
  2. BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("d:/a.txt"))));
  3. String s;
  4. //一次读取一行
  5. while((s = reader.readLine()) != null){
  6. System.out.println(s);
  7. }
  8. reader.close();
  9. } catch (FileNotFoundException e) {
  10. e.printStackTrace();
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  1. try {
  2. BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("d:/b.txt"))));
  3. //使用输出流写入数据
  4. writer.write("这是我新建的文本\r\n");
  5. //换行
  6. //writer.newLine();
  7. writer.write("又一段新的内容");
  8. writer.flush();
  9. writer.close();
  10. } catch (FileNotFoundException e) {
  11. e.printStackTrace();
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. }


自定义键盘接受
  1. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));



序列化 及 反序列化            ObjectInputStream          ObjectOutputStream
       序列化的对象要使用 Serializable接口
  1. import java.io.Serializable;
  2. public class User implements Serializable{
  3. private int userId;
  4. private String name;
  5. public User(int userId, String name) {
  6. super();
  7. this.userId = userId;
  8. this.name = name;
  9. }
  10. public int getUserId() {
  11. return userId;
  12. }
  13. public void setUserId(int userId) {
  14. this.userId = userId;
  15. }
  16. public String getName() {
  17. return name;
  18. }
  19. public void setName(String name) {
  20. this.name = name;
  21. }
  22. }
添加两个实例对象(user)到 list 集合里
  1. User user1 = new User(1001, "tom");
  2. User user2 = new User(1002, "jack");
  3. ArrayList<User> list = new ArrayList<User>();
  4. list.add(user1);
  5. list.add(user2);
进行序列化保存
  1. try {
  2. ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(new File("d:/users.data")));
  3. //将对象通过输出流进行序列化保存
  4. //序列化对象必须实现序列化接口
  5. output.writeObject(list);
  6. output.flush();
  7. output.close();
  8. } catch (Exception e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. }

反序列化读取文件
  1. try {
  2. ObjectInputStream input = new ObjectInputStream(new FileInputStream(new File("d:/users.data")));
  3. ArrayList<User> list = (ArrayList<User>) input.readObject();
  4. input.close();
  5. for(User user : list){
  6. System.out.println(user.getUserId()+"\t"+user.getName());
  7. }
  8. } catch (FileNotFoundException e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. } catch (IOException e) {
  12. // TODO Auto-generated catch block
  13. e.printStackTrace();
  14. } catch (ClassNotFoundException e) {
  15. // TODO Auto-generated catch block
  16. e.printStackTrace();
  17. }


0 0