使用IO流读写文件

  

package com.niit;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Exam1
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        //构建file对象 ,参数表示文件所在的路径
        File file = new File("d:\\niit.log");
        
        //判断文件是否存在
//        if(file.exists())
//        {
//            System.out.println("文件存在");
//        }
//        else
//        {
//            System.out.println("文件不存在");
//        }
        //判断文件是否是单个的文件
        System.out.println(file.isFile());
        //判断文件是否是文件夹
        System.out.println(file.isDirectory());
        //获取文件的绝对路径
        System.out.println(file.getAbsolutePath());
        //获取文件名
        System.out.println(file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("\\")+1,file.getAbsolutePath().lastIndexOf(".")));
        //获取文件完整的名称包括后缀名
        System.out.println(file.getName());
        //获取文件所在的相对路径
        System.out.println(file.getParent());
        //获取文件所在盘符的大小空间
        System.out.println(file.getTotalSpace());
        //获取文件所在盘符的可用空间
        System.out.println(file.getFreeSpace());
        System.out.println(file.getUsableSpace());
        //获取文件自身的字节数
        System.out.println(file.length());
        //是否隐藏文件
        System.out.println(file.isHidden());
        //是否可读
        System.out.println(file.canRead());
        //设置文件是否可写(只读性的设置)
        file.setWritable(false);
        //获取文件最后次修改的时间
        System.out.println(file.lastModified());
        System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(file.lastModified())));
    }

}
File 文件属性
package com.niit;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class Exam3
{
    /**
     * 根据指定路径搜索显示所有的文件信息
     * @param path
     */
    public void showFiles(String path)
    {
        //通过路径构建文件
        File file = new File(path);
        //判断文件是否存在
        if(file.exists())
        {
            //打印输出当前文件的路径
            System.out.println(file.getAbsolutePath());
            //判断是否是文件夹
            if(file.isDirectory())
            {
                //判断文件夹中是否有文件
                File[] files = file.listFiles();
                if(files != null)
                {
                    //遍历子文件
                    for(File childFile : files)
                    {
                        showFiles(childFile.getAbsolutePath());
                    }
                }
            }
        }
        else
        {
            System.out.println("文件不存在!");
        }
    }
    /**
     * @param args
     */
    /**
     * 创建文件
     */
    public void createFile(String path,String fileName)
    {
        //创建文件对象
        File file = new File(path, fileName);
        //判断文件是否存在
        if(file.exists())
        {
            System.out.println("文件已经存在");
        }
        else
        {
            //创建文件
            try
            {
                file.createNewFile();
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    /**
     * 创建文件夹
     * @param path
     */
    public void createDirectroy(String path, String diretroyName)
    {
        File file = new File(path, diretroyName);
        //判断是否存在
        if(!file.exists())
        {
            //创建文件夹
            file.mkdir();
        }
        else
        {
            System.out.println("文件夹已经存在");
        }
    }
    /**
     * 拷贝文件
     * @param sourcePath 复制文件的路径  如:D:/
     * @param fileName 文件名  如:back.jpg
     * @param newPath 复制到的位置  如:E:/
     */
    public void copyFile(String sourcePath, String fileName, String newPath)
    {
        //创建复制的文件
        File sourceFile = new File(sourcePath,fileName);
        //判断文件是否存在
        if(sourceFile.exists())
        {
            File newFile = new File(newPath,fileName);
            //如果文件存在,判断文件的类型
            if(sourceFile.isFile())
            {
                //如果是单个的文件,使用流读写文件
                try
                {
                    //构建输入流读取复制的文件
                    BufferedInputStream input = new BufferedInputStream(new FileInputStream(sourceFile),1024*1024*10);
                    //构建输出流写出文件
                    BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(newFile),1024*1024*10);
                    int data;
                    while((data = input.read()) != -1)
                    {
                        output.write(data);
                    }
                    //关闭流
                    output.flush();
                    output.close();
                    input.close();
                    
                } catch (FileNotFoundException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            else
            {
                //如果是文件夹,新建文件夹
                newFile.mkdir();
                //判断文件夹中是否还有子文件
                File[] files = sourceFile.listFiles();
                //遍历子文件
                for(File childFile : files)
                {
                    //递归复制子文件
                    copyFile(childFile.getParent(), childFile.getName(), newFile.getAbsolutePath());
                }
            }
        }
    }
    /**
     * 剪切文件
     * @param sourcePath
     * @param fileName
     * @param newPath
     */
    public void cutFile(String sourcePath, String fileName, String newPath)
    {
        //
    }
    /**
     * 重命名
     * @param path
     * @param fileName
     * @param newName
     */
    public void renameFile(String path, String fileName, String newName)
    {
        //创建源文件
        File oldFile = new File(path, fileName);
        //判断源文件是否存在
        if(oldFile.exists())
        {
            //创建新文件
            File newFile = new File(path, newName);
            //判断新文件是否存在
            if(!newFile.exists())
            {
                //重命名
                oldFile.renameTo(newFile);
            }
            else
            {
                System.out.println("文件名已存在");
            }
            
        }
        else
        {
            System.out.println("文件不存在");
        }
        
    }
    /**
     * 删除文件
     * @param path
     * @param fileName
     */
    public void deleteFile(String path, String fileName)
    {
        //获取要删除的文件对象
        File file = new File(path,fileName);
        //判断文件是否存在
        if(file.exists())
        {
            //如果存在,判断该文件是文件还是文件夹
            if(file.isDirectory())
            {
                //如果是文件夹,获取该文件夹的子文件
                File[] files = file.listFiles();
                //递归删除子文件
                for(File childFile : files)
                {
                    deleteFile(childFile.getParent(), childFile.getName());
                }
            }
            //删除整个文件
            file.delete();
        }
    }
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        Exam3 exam = new Exam3();
        
        //exam.showFiles("d:/");
        
        //exam.createFile("d:/", "a");
        
        //exam.createDirectroy("d:/", "a");
        
        //exam.renameFile("d:/", "b.txt", "c.txt");
        
        //File file = new File("d:/a");
        //delete方法可以删文件和文件夹,但是文件夹的删除必要删除该文件中所有的子文件后才能删除
        //file.delete();

        //exam.deleteFile("d:/", "MySpace");
        
        exam.copyFile("d:/", "a", "e:/");
        
        
    }

}
文件操作
package com.niit;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.crypto.Data;

public class Exam4
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        
        /*********************字节流***********************/
//        try
//        {
//            //创建输入流,输入流用来读取文件字节信息
//            //参数表示读取的文件对象
//            FileInputStream input = new FileInputStream(new File("d:/a"));
//            //创建输入流,将信息进行输出
//            //参数表示输出的文件目标
//            FileOutputStream output = new FileOutputStream(new File("e:/a"));
//            //读取输入流中的信息
//            //读取的字节
//            int data;
//            
//            while((data = input.read()) != -1)
//            {
//                //将读取的信息通过输出流完成输出
//                output.write(data);
//            }
//            //清空输出流
//            output.flush();
//            //关闭输出流
//            output.close();
//            //关闭输入流
//            input.close();
//            
//        } catch (FileNotFoundException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        
        /*****************字节缓冲流*********************/
//        try
//        {
//            //缓冲字节流依赖于字节流来构建
//            BufferedInputStream buffInput = new BufferedInputStream(new FileInputStream(new File("d:/back.jpg")));
//            //缓冲输出流
//            BufferedOutputStream buffOutput = new BufferedOutputStream(new FileOutputStream(new File("e:/back.jpg")));
//            int data;
//            while((data = buffInput.read()) != -1)
//            {
//                buffOutput.write(data);
//            }
//            buffOutput.flush();
//            buffOutput.close();
//            buffInput.close();
//        } catch (FileNotFoundException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        
        /*******************FileInputStream字节流实现缓冲*********************/
        try
        {
            FileInputStream input = new FileInputStream(new File("d:/back.jpg"));
            FileOutputStream output = new FileOutputStream(new File("e:/back.jpg"));
            //缓冲字节数组
            byte[] buffer = new byte[1024];
            //将输入流读取的文件信息读入到缓冲区中,返回读取的长度
            int len;
            while((len = input.read(buffer)) != -1)
            {
                
                output.write(buffer,0,len);
            }
            output.flush();
            output.close();
            input.close();
        } catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        /*********************Data字节流*************************/
//        //data可以在读写的时候按照特定的java格式进行数据的读写
//        try
//        {
//            DataInputStream input = new DataInputStream(new FileInputStream(new File("d:/back.jpg")));
//            DataOutputStream output = new DataOutputStream(new FileOutputStream(new File("e:/back.jpg")));
//            int data;
//            while((data = input.read()) != -1)
//            {
//                output.write(data);
//            }
//            output.flush();
//            output.close();
//            input.close();
//        } catch (FileNotFoundException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }

}
字节流
package com.niit;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Exam5
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
//        User user = new User(1001, "tom");
//        
//        //通过序列化保存数据
//        try
//        {
//            ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(new File("d:/temp.tmp")));
//            output.writeObject(user);
//            output.flush();
//            output.close();
//            
//        } catch (FileNotFoundException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        
        //通过反序列化对之前保存的数据进行对象的转换
//        try
//        {
//            ObjectInputStream input = new ObjectInputStream(new FileInputStream(new File("d:/temp.tmp")));
//            //读取文件中的对象
//            User user = (User)input.readObject();
//            input.close();
//            System.out.println(user.getUserId());
//            System.out.println(user.getUserName());
//        } catch (FileNotFoundException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (ClassNotFoundException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }

    }

}
序列化
package com.niit;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Exam6
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        /*******************字符流  用来读写文本文件*********************/
//        try
//        {
//            //创建字符输入流,字符流的构建依赖于字节流,InputStreamReadder是字节流通向字符流的桥梁
//            //不能使用字符流读取使用字节描述的文件信息,如图片,音频文件,视频文件
//            InputStreamReader reader = new InputStreamReader(new FileInputStream(new File("d:/test.txt")));
//            //创建字符输出流
//            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("e:/test.txt")));
//            int data;
//            while((data = reader.read()) != -1)
//            {
//                writer.write(data);
//                //System.out.println(data);
//            }
//            writer.flush();
//            writer.close();
//            reader.close();
//            
//        } catch (FileNotFoundException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        
        
        /********************缓冲字符流********************/
//        try
//        {
//            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("d:/集合项目.txt"))));
//            
//            String str = "";
//            //每次读取一行
//            while((str = reader.readLine()) != null)
//            {
//                System.out.println(str);
//            }
//            reader.close();
//        } catch (FileNotFoundException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        
        try
        {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("d:/my.txt"))));
            writer.write("自定义文本");
            //换行
            writer.newLine();
            writer.write("hello niit");
            writer.flush();
            writer.close();
        } catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
字符流

 

posted @ 2018-02-04 17:43  亲爱的阿道君  阅读(358)  评论(0编辑  收藏  举报