Java File类(文件的读取,写入,复制与重命名)

文件的重命名   file.reNameTo()

public boolean renameTo(File dest)
重新命名此抽象路径名表示的文件。

此方法行为的许多方面都是与平台有关的:重命名操作无法将一个文件从一个文件系统移动到另一个文件系统,dest为新命名的抽象文件

  

public boolean ReName(String path,String newname) {//文件重命名
        //Scanner scanner=new Scanner(System.in);
        File file=new File(path);
        if(file.exists()) {
        File newfile=new File(file.getParent()+File.separator+newname);//创建新名字的抽象文件
        if(file.renameTo(newfile)) {
            System.out.println("重命名成功!"); 
            return true;
        }
        else {
            System.out.println("重命名失败!新文件名已存在");
            return false;
        }
        }
        else {
            System.out.println("重命名文件不存在!");
            return false;
        }
    
    }

文件内容的读取

        File f2=new File(f1,"test.txt");//第一个参数为一个目录文件,第二个参数为要在当前f1目录下要创建的文件
        
        InputStreamReader reader=new InputStreamReader(new FileInputStream(f2),"GBK");
        BufferedReader bfreader=new BufferedReader(reader);
        String line;
        while((line=bfreader.readLine())!=null) {//包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null
            System.out.println(line);
        }
        

以上方法用于读取文本类文件

  FileInputStream 从文件系统中的某个文件中获得输入字节。哪些文件可用取决于主机环境。

InputStreamReader 是字节流通向字符流的桥梁 第二个参数可以设置字符集

BufferedReader 内包装 InputStreamReader   从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。

建议用 BufferedReader 包装所有其 read() 操作可能开销很高的 Reader(如 FileReader 和 InputStreamReader)

文件的写入

File f1=new File("H://asc//");//传入文件/目录的路径
        File f2=new File(f1,"test.txt");//第一个参数为一个目录文件,第二个参数为要在当前f1目录下要创建的文件
        
        PrintWriter printWriter =new PrintWriter(new FileWriter(f2,true),true);//第二个参数为true,从文件末尾写入 为false则从开头写入
        printWriter.println("I am your father");
        printWriter.close();//记得关闭输入流
        

使用 FileWriter写入字符流    如果要写入诸如图像数据之类的原始字节的流使用FileOutputStream 。

FileWriter

public FileWriter(String fileName,
                  boolean append)
参数:fileName - 一个字符串,表示与系统有关的文件名。append - 一个 boolean 值,如果为 true,则将数据写入文件末尾处,而不是写入文件开始处。

PrintWriter

public PrintWriter(OutputStream out,
                   boolean autoFlush)
autoFlush - boolean 变量;如果为 true,则 println、 printf 或 format 方法将自动刷新输出缓冲区 如果没有这个参数或者为 false 需要刷新缓冲输入区 fllush()




文件/文件夹的复制

文件的复制采用的思路是 先在目标路径下创建好空文件 在利用输入输出流 将从源文件中读取到的数据写入到新文件中

public void copyFile(String oldfilepath,String newpath) {//复制文件
        File oldfile=new File(oldfilepath);
        File newfile=new File(newpath+File.separator+oldfile.getName());//创建新抽象文件
        if(!oldfile.exists()||!oldfile.isFile()) {
            System.out.println("复制文件莫得¿¿¿");
            return;
        }
        if(newfile.exists()) {//新文件路径下有同名文件
            System.out.println("是否覆盖原有文件¿(y不覆盖|n覆盖)");
            Scanner scanner=new Scanner(System.in);
            String string=scanner.nextLine();
            if(string=="n") {
                newfile.delete();
                try {
                    newfile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            else {
                newfile=new    File(newpath+File.separator+"(1)"+newfile.getName());
                try {
                    newfile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        else {
                try {
                    newfile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        
        try {
            FileInputStream fin=new FileInputStream(oldfile);//输入流
            try {
                FileOutputStream fout=new FileOutputStream(newfile,true);//输出流
                byte[]b=new byte[1024];
                try {
                    while((fin.read(b))!=-1) {//读取到末尾 返回-1 否则返回读取的字节个数
                        fout.write(b);
                    }
                    fin.close();
                    fout.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

文件夹的复制

如果是空文件夹倒还好说,直接新建同名文件夹 。但如果是含有文件内容的文件夹的话  需要使用深度优先遍历文件夹。 如果是文件夹 就在对应路径下创建空文件夹 再递归调用函数遍历自身   如果是文件 则直接复制过来

    
    public void dfs(File f1,File f2) {//f1要复制的文件    f2要复制到的路径
        
        if(f1.isFile()&&f1.exists()) {//文件
            copyFile(f1.getAbsolutePath(), f2.getAbsolutePath());
            return;
        }
        if(f1.isDirectory()) {
            File file2=new File(f2.getAbsoluteFile()+File.separator+f1.getName());
            
            file2.mkdirs();
            String []list=f1.list();
            for (int i = 0; i < list.length; i++) {
                File file1=new File(f1.getAbsoluteFile()+File.separator+list[i]);
                dfs(file1, file2);
            }
        }
    }
    
    public void copydir(String oldfilepath,String newfilepath) {//复制文件夹
        File oldfile=new File(oldfilepath);
        File newfile=new File(newfilepath+File.separator+oldfile.getName());
        if(!oldfile.exists()||!oldfile.isDirectory()) {
            System.out.println("此文件夹不存在!");
            return;
        }
        
        if(newfile.exists()) {
            System.out.println("是否覆盖原有文件夹¿(y不覆盖|n覆盖)");
            Scanner scanner=new Scanner(System.in);
            String string=scanner.nextLine();
            if(string=="n") {
                deleteFile(newfile.getAbsolutePath());
                
            }
            else
                return;
        }
        //dfs
        dfs(oldfile, new File(newfilepath));
            
        return;
            
    }

注意 再使用输入输出流后记得 用close()函数关闭 输入输出流.  如果一个文件被打开着 没被关闭  另一个程序想要访问时 就会报错异常

文件输出流是用于将数据写入 File 或 FileDescriptor 的输出流。文件是否可用或能否可以被创建取决于基础平台。
特别是某些平台一次只允许一个 FileOutputStream(或其他文件写入对象)打开文件进行写入。在这种情况下,如果所涉及的文件
已经打开,则此类中的构造方法将失败

原文地址:https://www.cnblogs.com/yellowbananame/p/8946976.html