Java File class (file reading, writing, copying and renaming)

File renaming file.reNameTo()

public boolean renameTo(File dest)
Renames the file represented by this abstract pathname.

Many aspects of this method's behavior are platform-dependent: rename operations cannot move a file from one filesystem to another, dest is the newly named abstract file

  

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);//Create an abstract file with a new name
         if (file.renameTo(newfile)) {
            System.out.println( "Rename succeeded!" ); 
             return  true ;
        }
        else {
            System.out.println( "Rename failed! New file name already exists" );
             return  false ;
        }
        }
        else {
            System.out.println( "Rename file does not exist!" );
             return  false ;
        }
    
    }

 

 

read file content

        File f2= new File(f1,"test.txt"); // The first parameter is a directory file, and the second parameter is the file to be created in the current f1 directory 
        
        InputStreamReader reader = new InputStreamReader( new FileInputStream( f2),"GBK" );
        BufferedReader bfreader=new BufferedReader(reader);
        String line;
        while ((line=bfreader.readLine())!= null ) { // A string containing the content of the line, without any line terminator, or null if the end of the stream has been reached 
            System.out.println(line) ;
        }
        

The above method is used to read text class files

  FileInputStream Get input bytes from a file in the filesystem. Which files are available depends on the host environment.

InputStreamReader is a bridge from byte stream to character stream The second parameter can set the character set

BufferedReader wraps InputStreamReader to read text from a character input stream, buffering individual characters, enabling efficient reading of characters, arrays, and lines.

It is recommended to wrap all Readers whose read() operations may be expensive (such as FileReader and InputStreamReader) with a BufferedReader

 

 

file writing

File f1= new File("H://asc//"); // The path of incoming file/directory 
        File f2= new File(f1,"test.txt"); // The first parameter is a directory file, the second parameter is the file to be created in the current f1 directory 
        
        PrintWriter printWriter = new PrintWriter( new FileWriter(f2, true ), true ); // The second parameter is true, and it is false to write from the end of the file Then write from the beginning 
        printWriter.println("I am your father" );
        printWriter.close();//Remember to close the input stream
        

Writing to a character stream with FileWriter If you want to write a stream of raw bytes such as image data use FileOutputStream.

FileWriter

public FileWriter(String fileName,
                  boolean append) 
parameters:fileName  - A string representing the system-dependent filename. append - A boolean value that, if true  true, writes data at the end of the file rather than at the beginning of the file.

PrintWriter

public PrintWriter(OutputStream out,
                   boolean autoFlush) -
autoFlush  boolean variable; if true, the  printlnprintf  or  format  method will automatically flush the output buffer. If this parameter is absent or false, the buffer input area needs to be flushed . The idea is to first create an empty file in the target path, and then use the input and output streams to write the data read from the source file to a new file








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( "Copy file ¿¿¿" );
             return ;
        }
        if (newfile.exists()) { // There is a file with the same name in the new file path 
            System.out.println("Whether to overwrite the original file ¿(y does not overwrite|n overwrite)" );
            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 ); // output stream 
                byte []b= new  byte [1024 ];
                 try {
                     while ((fin.read(b))!=-1) { // read to the end Return -1 otherwise return the number of bytes read 
                        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();
        }
        
    }

copy of folder

If it is an empty folder, it is better to say, just create a new folder with the same name. But if it is a folder with file content, you need to use depth-first traversal of the folder. If it is a folder, create an empty folder in the corresponding path and then recursively call the function to traverse itself. If it is a file, copy it directly

    
    public  void dfs(File f1,File f2) { // The path to which the file f2 to be copied by f1 is to be copied
        
        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( "This folder does not exist!" );
             return ;
        }
        
        if(newfile.exists()) {
            System.out.println( "Whether to overwrite the original folder ¿ (y does not overwrite|n overwrite)" );
            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;
            
    }

Note that after using the input and output streams, remember to use the close() function to close the input and output streams. If a file is opened but not closed, another program will report an error exception when it wants to access it

A file output stream is the output stream used to write data to a File or FileDescriptor. Whether the file is available or can be created depends on the underlying platform.
In particular some platforms only allow one FileOutputStream (or other file writing object) to open a file for writing at a time. In this case,
the constructor in this class will fail if the file in question is already open

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324850736&siteId=291194637