Java file Class (read, write, copy, and rename files)

Source: Internet
Author: User

Renaming a file File.renameto ()

Renameto (File dest)
renames the file represented by this abstract path name.

Many aspects of this method's behavior are platform-related: Rename operations cannot move a file from one file system to another, dest to a newly named abstract file

  

 Public BooleanReName (String path,string newname) {//file Rename//Scanner scanner=new Scanner (system.in);File file=NewFile (path); if(File.exists ()) {file NewFile=NewFile (File.getparent () +file.separator+newname);//abstract file that creates a new nameif(File.renameto (NewFile)) {System.out.println ("Rename succeeded!" "); return true; }        Else{System.out.println ("Renaming failed!" The new file name already exists "); return false; }        }        Else{System.out.println ("Renaming file does not exist!" "); return false; }        }

Read the contents of the file

        File f2=new file (F1, "test.txt"); // The first parameter is a directory file, the second parameter is the file to be created under 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 contents of the row, without any line terminator, or null System.out.println if the end of the stream has been reached            ;        }        

The above method is used to read the text class file

  FileInputStreamGets the input bytes from a file in the file system. Which files are available depends on the host environment.

InputStreamReader is a bridge of byte flow to a character stream the second parameter sets the character set

BufferedReader Inner wrapper InputStreamReader reads text from the character input stream, buffering individual characters, enabling efficient reading of characters, arrays, and rows.

It is recommended to use BufferedReader to wrap all of their read () operations with potentially expensive Reader (such as FileReader and InputStreamReader)

Write to File

File f1=new file ("h://asc//"); // Path to 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 under the current F1 directory   = new PrintWriter (new FileWriter (F2, True), true);                  // The second argument is true, writing from the end of the file to False is written        from the beginning Printwriter.println ("I am Your Father");        Printwriter.close ();//Remember to close        the input stream

Use FileWriter to write a stream of characters if you want to write raw bytes such as data using FileOutputStream.

FileWriter
FileWriter (String FileName,                  boolean append)
Parameters: fileName -a string that represents the system-related file name. append-A Boolean value that, if it is true , writes data to the end of the file, rather than to the beginning of the file.
PrintWriter
PrintWriter (OutputStream out,                   boolean autoflush)
autoFlush-Boolean variable; If true, the println, printf , or format method will automatically flush the output buffer if there is no parameter or false Need to refresh buffer input area Fllush ()




Copy of File/folder

The idea of copying files is to create an empty file in the target path to write the data read from the source file to the new file using the input and output stream

 Public voidCopyFile (String oldfilepath,string NewPath) {//Copying FilesFile oldfile=NewFile (Oldfilepath); File NewFile=NewFile (Newpath+file.separator+oldfile.getname ());//Create a new abstract file        if(!oldfile.exists () | |!Oldfile.isfile ()) {System.out.println ("??? To copy Files"); return; }        if(Newfile.exists ()) {//file with the same name under the new file pathSystem.out.println ("Do you want to overwrite the original file? (y not overwrite |n)"); Scanner Scanner=NewScanner (system.in); String String=Scanner.nextline (); if(string== "n") {newfile.delete (); Try{newfile.createnewfile (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }            Else{NewFile=NewFile (newpath+file.separator+ "(1)" +newfile.getname ()); Try{newfile.createnewfile (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        }        Else {                Try{newfile.createnewfile (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }                Try{fileinputstream fin=NewFileInputStream (Oldfile);//input Stream            Try{fileoutputstream Fout=NewFileOutputStream (NewFile,true);//output Stream                byte[]b=New byte[1024]; Try {                     while((Fin.read (b))!=-1) {//reads to the end returns 1 otherwise returns the number of bytes readFout.write (b);                    } fin.close ();                Fout.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }                            } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); }                    } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }

Replication of folders

If the empty folder is OK, just create a new folder with the same name. However, if it is a folder containing the contents of the file, you need to traverse the folder with depth precedence. If it is a folder, create an empty folder under the corresponding path and recursively call the function to traverse itself if it is a file, copy it directly.

         Public voidDFS (File f1,file f2) {//F1 the file to be copied F2 the path to be copied to                if(F1.isfile () &&f1.exists ()) {//fileCopyFile (F1.getabsolutepath (), F2.getabsolutepath ()); return; }        if(F1.isdirectory ()) {File file2=NewFile (F2.getabsolutefile () +file.separator+f1.getname ());            File2.mkdirs (); String []list=f1.list ();  for(inti = 0; i < list.length; i++) {File file1=NewFile (F1.getabsolutefile () +file.separator+List[i]);            DFS (File1, file2); }        }    }         Public voidCopydir (String oldfilepath,string newfilepath) {//Copy FolderFile oldfile=NewFile (Oldfilepath); File NewFile=NewFile (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 ("Overwrite the original folder? (y do not overwrite |n)"); Scanner Scanner=NewScanner (system.in); String String=Scanner.nextline (); if(string== "n") {DeleteFile (Newfile.getabsolutepath ()); }            Else                return; }        //DFSDFS (Oldfile,NewFile (Newfilepath)); return; }

Note Use the close () function to close the input and output stream after you have used the input and output stream again. If a file is opened and not closed, another program will have an error when it wants to access it.

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

Java file Class (read, write, copy, and rename files)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.