Java File类提供的方法与操作

File类

File类事java.io包中唯一代表磁盘文件本身的对象。File类定义了一些与平台无关的方法来操作文件,可以通过调用File类中的方法,实现创建、删除、重命名文件等操作。File类的对象主要用来获取文件本身的一些信息,如文件所在的目录、文件的长度、文件读写权限等。数据流可以将数据写入到文件中,文件也是数据流最常用的数据媒体。

1.文件的创建与删除

可以使用File类创建一个文件对象。通常使用以下三种方法来创建文件对象。

(1)File(String pathname)

该构造方法通过将给定路径名字字符串转换为抽象路径名来创建一个新的File实例。例如:

File file = new File("d:/1.txt");

2.File类提供的方法

File类提供了很多方法以获取文件本身的信息,常用的方法如下:

方法返回值说明
getName()String获取文件的名称
canRead()boolean判断文件是否为可读的
canWrite()boolean判断文件是否可被写入
exists()boolean判断文件是否存在
delete()void删除文件
length()long获取文件的长度(以字节为单位)
getAbsolutePath()String获取文件的绝对路径
getParent()String获取文件的父路径
isFile()boolean获取文件的名称
isDirectory()boolean判断文件是否为一个目录
isHidden()boolean判断文件是否为隐藏文件
lastModified()long获取文件最后修改时间

3.文件输入/输出流

程序运行期间,大部分数据都在内存中进行操作,当程序结束或关闭时,这些数据将消失。如果需要将数据永久保存,可以使用文件输入/输出流与指定文件建立连接,将需要的数据永久保存到文件中。

FileInputStream 与 FileOutputStream类

FileInputStream类与FileOutputStream类都用来操作磁盘文件。

FileInputStream类常用的构造方法如下:

  • FileInputStream(String name)
  • FileInputStream(File file)

第一个构造方法使用给定的文件名name创建一个FileInputStream对象,第二个构造方法使用File对象创建FileInputStream对象。第一个构造方法比较简单,但第二个构造方法允许在把文件链接输入流之前对文件作进一步分析。

FileOutputStream类有与FileInputStream类相同的参数构造方法,创建一个FileOutputStream对象时,可以指定不存在的文件名,但此文件不能是一个已被其他程序打开的文件。例如:

public class FileTest{
        public static void main(String[]args){
                File file = new File("world.txt");
                try{
                        FileOutputStream out = new FileOutputStream(file);
                        byte buy[] = "我有一头小毛驴,我从来也不骑。".getBytes();
                        out.write(buy);
                        out.close();
                } catch(Exception e) {
                        e.printStackTrace();
                }
                try{
                        //创建FileInputStream类对象
                        FileInputStream in = new FileInputStream(file);
                        byte byt[] = new byte[1024]; //创建byte数组
                        int len = in.read(byt); //从文件中读取信息
                        System.out.println("文件中的信息是:" + new String(byt, 0, len))
                        in.close();
                } catch(Exception e) {
                        e.printStackTrace();
                }
        }
}

4.FileReader和FileWriter类

使用FileOutputStream类向文件中写入数据与使用FileInputStream类从文件中将内容读出来,都存在一点不足,即这两个类都只提供了对字节或字节数组的读取方法。由于汉字在文件中占用两个字节,如果使用字节流,读取不好可能会出现乱码的现象,此时采用字符流Reader或Writer类即可避免这种现象。

FileReader流顺序地读取文件,只要不关闭流,每次调用read()方法就顺序地读取源中其余的内容,直到源的末尾或流被关闭。

本实例创建Swing窗体,单机“写入文件”按钮将实现文本框中的数据写入磁盘文件中,单机“读取文件”按钮,系统将磁盘文件中的信息显示在文本框里。

public class Ftest extends JFrame{
        private static final long serialVersionUID = 1L;
        private JPanel jContentPane = null; //创建面板对象
        private JTextArea jTextArea = null; //创建文本域对象
        private JPanel controlPanel = null; //创建面板对象
        private JButton openButton = null; //创建按钮对象
        private JButton closeButton = null; //创建按钮对象
        private JButton getOpenButton(){
                if(openButton == null){
                        openButton = new JButton();
                        openButton.setText("写入文件"); //修改按钮的提示信息
                        openButton.addActionListener(new ActionListener(){
                                //按钮的单机事件
                                public void actionPerformed(ActionEvent e){
                                        File file = new File("world.txt"); //创建文件对象
                                        try{
                                                FileWriter out = new FileWriter(file); //创建FileWriter对象
                                                String s = jTextArea.getText(); //获取文本域中文本
                                                out.write(s); //将信息写入磁盘文件
                                                out.close(); //将流关闭
                                        catch(Exception e1){
                                                e1.printStackTrace();
                                        }
                                }
                        });
                }
                return openButton;
        }
        private JButton getCloseButton(){
                if(closeButton == null){
                        closeButton = new JButton();
                        closeButton.setText("读取文件"); //修改按钮的提示信息
                        closeButton.addActionListener(new ActionListener(){
                                //按钮的单击事件
                                public void actionPerformed(ActionEvent e){
                                        File file = new File("world.txt"); //创建文件对象
                                        try{
                                                FileReader in = new FileReader(file); //创建FileReader对象
                                                char byt[] = new char[1024]; //创建char型数组
                                                int len = in.read(byt); //将字节读入数组
                                                jTextArea.setText(new String(byt, 0, len)); //设置文本域的显示信息
                                                in.close(); //关闭流
                                        }catch(Exception e1){
                                                e1.printStackTrace();
                                        }
                                }
                        });
                }
                return closeButton;
        }
        public Ftest(){
                super();
                initialize();
        }
        private void initilize(){
                this.setSize(300,200);
                this.setContentPane(getJContentPane());
                this.setTitle("JFrame");
        }
        private JPanel getJContentPane(){
                if(jContentPane == null){
                        jContentPane = new JPanel();
                        jContentPane.setLayout(new BorderLayout());
                        jContentPane.add(getJTextArea(), BorderLayout.CENTER);
                        jContentPane.add(getControlPanel(),BorderLayout.SOUTH);
                }
                return jContentPane;
        }
        public static void main(String[] args){ //主方法
                Ftest thisClass = new Ftest(); //创建本类对象
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true); //设置该窗体的显示状态
        }
}

原文地址:https://blog.csdn.net/weixin_44860226/article/details/127789334