Java file read and write operations Daquan

Source: Internet
Author: User

I. Obtaining information from console user input

//can return the user input information, the disadvantage is that the Chinese input is not supported, need to be further improved     PublicString Getinputmessage ()throwsIOException ... {System.out.println ("Please enter your command:"); bytebuffer[]=New byte[1024]; intCount=System.in.read (buffer); Char[] Ch=New Char[Count-2];//The last two bits are the Terminator, delete the          for(inti=0;i<count-2;i++) Ch[i]=(Char) Buffer[i]; String Str=NewString (CH); returnstr; }     

two. Copying Files

Copying files as a file stream

     
Support Chinese processing, and can copy many types, such as Txt,xml,jpg,doc and other formats
Public voidCopyFile (String src,string dest)throwsIOException ... {FileInputStream in=NewFileInputStream (SRC); File File=NewFile (dest); if(!file.exists ()) file.createnewfile (); FileOutputStream out=Newfileoutputstream (file); intC; bytebuffer[]=New byte[1024]; while(C=in.read (buffer))!=-1)... { for(inti=0;i<c;i++) Out.write (Buffer[i]); } in.close (); Out.close (); }

Three. Writing files

1. write files using PrintStream

 Public void Printstreamdemo () ... {         try  ... {             FileOutputStreamout =new fileoutputstream ("D:/test.txt");             PrintStream p=new  PrintStream (out);               for (int i=0;i<10;i++)                 p.println ("This was" +i+ "line");          Catch (FileNotFoundException e) ... {             e.printstacktrace ();         }     }

2. write files using StringBuffer

//This method can set the encoding used to solve the Chinese problem effectively .     Public voidStringbufferdemo ()throwsIOException ... {File File=NewFile ("/root/sms.log"); if(!file.exists ()) file.createnewfile (); FileOutputStream out=NewFileOutputStream (file,true);  for(inti=0;i<10000;i++)...... {StringBuffer SB=NewStringBuffer (); Sb.append ("This is the first" +i+ "line: The various methods described earlier are not used, why is it always a strange question"); Out.write (Sb.tostring (). GetBytes ("Utf-8"));     } out.close (); }

Four. Read the file

1. Using FileInputStream to read files

 PublicString Fileinputstreamdemo (String path)throwsIOException ... {File File=NewFile (path); if(!file.exists () | |file.isdirectory ())Throw NewFileNotFoundException (); FileInputStream FIS=Newfileinputstream (file); byte[] buf =New byte[1024]; StringBuffer SB=NewStringBuffer ();  while((Fis.read (BUF))!=-1)... {Sb.append (NewString (BUF)); BUF=New byte[1024];//regenerate to avoid duplication with last-read data         }         returnsb.tostring (); }

2. Read with BufferedReader

     //in IO operation, using BufferedReader and bufferedwriter efficiency will be a bit higher      PublicString Bufferedreaderdemo (String path)throwsIOException ... {File File=NewFile (path); if(!file.exists () | |file.isdirectory ())Throw NewFileNotFoundException (); BufferedReader BR=NewBufferedReader (Newfilereader (file)); String Temp=NULL; StringBuffer SB=NewStringBuffer (); Temp=Br.readline ();  while(temp!=NULL)... {Sb.append (temp+" "); Temp=Br.readline (); }         returnsb.tostring (); }

3. Reading an XML file with dom4j

 Public throws documentexception, IOException ... {         file file=new  file (path);          New BufferedReader (new  filereader (file));          New Saxreader ();          = (Document) saxreader.read (BufferedReader);         Bufferedreader.close ();          return document;     }

Five. File renaming

 Public voidrenamefile (String path,string oldname,string newname) ... {         if(!oldname.equals (newname)) ... {//The new file name and the previous file name are not the same, it is necessary to renameFile oldfile=NewFile (path+ "/" +oldname); File NewFile=NewFile (path+ "/" +newname); if(Newfile.exists ())//If there is already a file and the new file name in the directory, renaming is not allowedSystem.out.println (newname+ "already exists! "); Else...             {Oldfile.renameto (newfile); }         }              }

Vi. Transfer file directory (cut)

//The transfer file directory is not the same as copying a file, the copy file is copied after both directories exist for the file, and the transfer file directory is transferred, only the file exists in the new directory.       Public voidChangedirectory (String filename,string oldpath,string NewPath,Booleancover) ... {         if(!oldpath.equals (NewPath)) ... {File Oldfile=NewFile (oldpath+ "/" +filename); File NewFile=NewFile (newpath+ "/" +filename); if(Newfile.exists ()) ... {//if the file to be transferred is already present in the pending transfer directory                 if(cover)//coverOldfile.renameto (NewFile); ElseSystem.out.println ("Already exists under the new directory:" +filename); }             Else...             {Oldfile.renameto (newfile); }         }            }

Seven. Create a File/folder

1. Create a folder

 Public void Createdir (String path) ... {         file dir=new  file (path);          if (! dir.exists ())             Dir.mkdir ();     }

2. Create a new file

 Public void throws IOException ... {         file file=new file (path+ "/" +filename);          if (! file.exists ())             File.createnewfile ();     }

Eight. deleting files (directories)
1. deleting files

 Public void delfile (String path,string filename) ... {         file file=new file (path+ "/" +filename);          if (File.exists () &&file.isfile ())             file.delete ();     }

2. Deleting a directory

//to delete a directory with the Delete () method of the file class, you must ensure that there are no files or subdirectories in the directory, otherwise the deletion fails, so in the actual application we are going to delete the directory and must use recursion to delete all subdirectories and files under that directory, and then delete the directory.       Public voidDeldir (String path) ... {File dir=NewFile (path); if(Dir.exists ()) ... {file[] tmp=Dir.listfiles ();  for(inti=0;i<tmp.length;i++)... {                 if(Tmp[i].isdirectory ()) ... {Deldir (Path+"/"+tmp[i].getname ()); }                 Else...                 {Tmp[i].delete ();         }} dir.delete (); }     }

Java file read and write operations Daquan

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.