java-I/O(输入与输出)

1.输入/输出流

  1. InputString类是字节输流的抽象类,是所有字节输入流的父类。
read()      从输入流中读取数据的下一个字节。返回0-255范围内的int字节值,若后无字节,返回-1read(byte[] b)  从输入流中读入一定长度的字节,并以整数的形式返回字节数。
close()     关闭此输入流并释放与该流关联的所有系统资源。

2.OutputString类是字节输出流的抽象类,此抽象类表示输出字节流的所有类的超类。

write(int b)        将指定的字节写入此输出流。
write(byte[] b)     将b个字节从指定的byte数组写入此输出流。
write(byte[],int off,int len)       将指定byte数组中偏移off开始的len个字节写入此输出流。
flush()         彻底完成输出并清空缓存区。
close()         关闭输出流。

public class demo12 {

    public static void main(String[] args) throws IOException {

        File file1 = new File("E:/workspace/Demo/src/Demo/1.jpg");
        File file2 = new File("E:/workspace/Demo/src/Demo/2.jpg");

        FileInputStream input = new FileInputStream(file1);
        FileOutputStream output = new FileOutputStream(file2);

        int count = 0;
        while((count = inputStream.read())!=-1){
            outputStream.write(count);
        }
        inputStream.close();
        outputStream.close();
    }
}

File file = new File("E:/workspace/Demo/src/Demo/1.txt");
FileOutputStream output = new FileOutputStream(file);
byte byt[] = "3333333333".getBytes();
output.write(byt);  //将数组中的信息写入到文件中
output.close();

FileInputStream input = new FileInputStream(file);
byte but[] = new byte[1024];    //创建byte数组
int len = input.read(but);  //从文件中读取信息
System.out.println(""+new String(but,0,len));
input.close();

2.File类的常用方法

File类是java.io包中唯一代表磁盘文件本身的对象。

exits()         判断文件是否存在
isFile()        判断文件是否存在
canRead()       判断文件是否可读
canWrite()      判断文件是否可写
isHidden()      判断文件是否为隐藏文件
isDirectory()       判断文件是否为同一个目录

getName()       获取文件的名称
length()        获取文件的大小(字节数)
getpath()       获取文件的绝对路径
getParent()     获取文件的父路径
lastModified()  获取文件的最后修改时间

3.文件的创建与删除

1.createNewFile()   在指定位置创建一个空文件,成功就返回true,如果已存在就不创建然后返回false
2.mkdir()           在指定位置创建目录,这只会创建最后一级目录,如果上级目录不存在就抛异常。
3.mkdirs()          在指定位置创建目录,这会创建路径中所有不存在的目录。
4.renameTo(File dest)   重命名文件或文件夹,也可以操作非空的文件夹,文件不同时相当于文件的剪切,剪切时候不能操作非空的文件夹。移动/重命名成功则返回true,失败则返回false5.delete()  删除文件

public class demo12 {

    public static void main(String[] args) throws IOException {

        File file = new File("E:/workspace/Demo/src/Demo/word.jpg");
        System.out.println("目录分割符号:"+file.separator);
        if(file.exists()){
            file.delete();
            System.out.println("文件已删除");
        }else{
            try {
                file.createNewFile();
                System.out.println("文件已创建");
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

        // mkdir 创建一个单级文件夹  创建名字a的文件夹
        File dir = new  File("E:\\workspace\\File\\src\\file\\a");
        System.out.println("创建文件夹成功吗?"+dir.mkdir()); 

        //// mkdirs 创建一个多级文件夹  创建名字a的文件夹
        File dir1 = new File("E:\\workspace\\File\\src\\file\\aa\\bb");
        System.out.println("创建多级文件夹:"+ dir1.mkdirs());

        //renameTo()  如果目标文件与源文件是在同一个路径下,那么renameTo的作用是重命名, 
        //如果目标文件与源文件不是在同一个路径下,那么renameTo的作用就是剪切,而且还不能操作文件夹。 
        File destFile = new File("E:\\workspace\\File\\src\\file\\1.txt");
        System.out.println("重命名成功吗?"+file.renameTo(destFile)) ;
    }
}

4.文件夹的操作

文件夹相关:
staic File[] listRoots() 列出所有的根目录(Window中就是所有系统的盘符)
list() 返回目录下的文件或者目录名,包含隐藏文件。对于文件这样操作会返回null。
listFiles() 返回目录下的文件或者目录对象(File类实例),包含隐藏文件。对于文件这样操作会返回null。

list(FilenameFilter filter) 返回指定当前目录中符合过滤条件的子文件或子目录。对于文件这样操作会返回null。
listFiles(FilenameFilter filter)    返回指定当前目录中符合过滤条件的子文件或子目录。对于文件这样操作会返回nullpublic class demo16 {
    public static void main(String[] args) {
        File[] roots = File.listRoots();
        System.out.println("列出所有的根目录:"+Arrays.toString(roots));
        for(File file : roots){
            System.out.println(file);
        }

        //返回当前文件夹里的所有文件与文件夹存储到一个String类型 的数组中
        File file = new  File("E:\\workspace\\File\\src\\file");
        String[] fileNames = file.list(); 
        for(String fileName : fileNames){
            System.out.println(fileName);
        }

    // 返回当前文件夹里的所有文件与文件夹都使用了一个FIle对象描述,然后把这些File对象存储到一个FIle数组中返回
        File[] files = file.listFiles();
        for(File fileItem : files){
            System.out.println("文件名:"+ fileItem.getName());
    }
}

5.FileReader和FileWriter类

FileOutputStream类向文件写入数据与使用FileInputStream类从文件将内容读出来,都存在一点不足,两个类只提供了对字节或字节数组的读取方法。汉字占两个字节,读取不好容易乱码。

public class demo13 extends JFrame{

    private static final long serialVersionUID = 1L;
    private JPanel jContentPanel = null;
    private JPanel controlPanel = null;
    private JButton OpenButton = null;      //写入按钮
    private JButton CloseButton = null;     //读取按钮
    private JTextArea jTextArea = null;     //文本域

    //写入按钮
    public JButton getOpenButton(){
        if(OpenButton == null){
            OpenButton = new JButton();
            OpenButton.setText("写入文件");
            OpenButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    File file = new File("E:/workspace/Demo/src/Demo/1.txt");
                    try {
                        FileWriter out = new FileWriter(file);
                        String string = jTextArea.getText();
                        out.write(string);
                        out.close();
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
            });
        }
        return OpenButton;
    }

    //读取按钮
    public JButton getCloseJButton(){

        if(CloseButton == null){
            CloseButton = new JButton();
            CloseButton.setText("读取文件");
            CloseButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    File file = new File("E:/workspace/Demo/src/Demo/1.txt");
                    try {
                        FileReader input = new FileReader(file);
                        char byt[] = new char[1024];
                        int len = input.read(byt);
                        jTextArea.setText(new String(byt,0,len));
                        input.close();
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
            });
        }
        return CloseButton;
    }

    public demo13(){
        super();
        initialize();
    }

    //面板属性
    private void initialize(){
        this.setTitle("JFrame");
        this.setSize(500,500);
        this.setContentPane(getcontenPanel());
    }

    //总面板布局
    private JPanel getcontenPanel(){
        if(jContentPanel == null){
            jContentPanel = new JPanel();
            jContentPanel.setLayout(new BorderLayout());
            jContentPanel.add(getJAtextArea(),BorderLayout.CENTER);
            jContentPanel.add(getcontrolPanel(),BorderLayout.SOUTH);
        }
        return jContentPanel;
    }

    //按钮面板布局
    private JPanel getcontrolPanel(){
        if(controlPanel == null){
            controlPanel = new JPanel();
            controlPanel.setLayout(new BorderLayout());
            controlPanel.setBackground(Color.blue);
            controlPanel.add(getOpenButton(),BorderLayout.EAST);
            controlPanel.add(getCloseJButton(),BorderLayout.WEST);
        }
        return controlPanel;
    }

    //文本域面板
    private JTextArea getJAtextArea(){
        if(jTextArea == null){
            jTextArea = new JTextArea(40,40);
        }
        return jTextArea;
    }

    //main方法
    public static void main(String[] args) {
        demo13 jFrame = new demo13();
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }
}

6.BufferrdInputString 与 BufferedOutputString类


带缓存的输入/输出流
read()      读取单个字符
readLine()  读取一个文本行,并将其返回一个字符串,否则返回null.
flush()     刷新该流的缓存
newLine()   写入一个行分割符

public class demo1 {

    public static void main(String[] args) {

        String content[] = {"好久不见","最近好吗","常联系"};
        File file = new File("E:/workspace/Demo/src/Demo/1.txt");
        try {
            FileWriter fw = new FileWriter(file);
            BufferedWriter bufw = new BufferedWriter(fw);
            for(int k = 0;k<content.length;k++){
                bufw.write(content[k]);
                bufw.newLine();
            }
            bufw.close();
            fw.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        try {
            FileReader fr = new FileReader(file);
            BufferedReader bufr = new BufferedReader(fr);
            String s = null;
            int i = 0;
            while((s = bufr.readLine())!= null){
                i++;
                System.out.println("第"+i+"行"+s);
            }
            bufr.close();
            fr.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }   
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值