Java file read and write operations

Source: Internet
Author: User

I. Obtaining information from console user input

Public String Getinputmessage () throws IOException ... {
System.out.println ("Please enter your command:");
byte buffer[]=new byte[1024];
int count=system.in.read (buffer);
Char[] Ch=new char[count-2];//last two bits for terminator, delete do not
for (int i=0;i<count-2;i++)
ch[i]= (char) buffer[i];
String Str=new string (ch);
return str;
}
Can return the user input information, the disadvantage is that the Chinese input is not supported, and needs to be further improved.

two. Copying Files
1. Copying files as a file stream

public void CopyFile (String src,string dest) throws IOException ... {
FileInputStream in=new FileInputStream (SRC);
File File=new file (dest);
if (!file.exists ())
File.createnewfile ();
FileOutputStream out=new fileoutputstream (file);
int C;
byte buffer[]=new byte[1024];
while ((C=in.read (buffer))!=-1) ... {
for (int i=0;i<c;i++)
Out.write (Buffer[i]);
}
In.close ();
Out.close ();
}
This method has been tested, supports Chinese processing, and can replicate many types, such as Txt,xml,jpg,doc and many other formats.

Three. Writing files

1. write files using PrintStream


public void Printstreamdemo () ... {
Try ... {
FileOutputStream out=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
public void Stringbufferdemo () throws IOException ... {
File File=new file ("/root/sms.log");
if (!file.exists ())
File.createnewfile ();
FileOutputStream out=new FileOutputStream (file,true);
for (int i=0;i<10000;i++) ... {
StringBuffer sb=new StringBuffer ();
Sb.append ("This is the" +i+ "line: The various methods described above are not used, why is it always a strange question");
Out.write (Sb.tostring (). GetBytes ("Utf-8"));
}
Out.close ();
}
This method can set the encoding used to solve the Chinese problem effectively.
four. File renaming

public void RenameFile (String path,string oldname,string newname) ... {
if (!oldname.equals (newname)) ... {//New file name and previous file name are not the same, it is necessary to rename
File Oldfile=new file (path+ "/" +oldname);
File Newfile=new file (path+ "/" +newname);
if (newfile.exists ())//If the directory already has a file and the new file name is the same, it is not allowed to rename
System.out.println (newname+ "already exists! ");
else ... {
Oldfile.renameto (NewFile);
}
}
}

Five. Transfer Files directory
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 void Changedirectory (String filename,string oldpath,string newpath,boolean cover) ... {
if (!oldpath.equals (NewPath)) ... {
File Oldfile=new file (oldpath+ "/" +filename);
File Newfile=new file (newpath+ "/" +filename);
if (newfile.exists ()) ... {//If the file to be transferred is already present in the pending transfer directory
if (cover)//overwrite
Oldfile.renameto (NewFile);
Else
System.out.println ("already exists under the new directory:" +filename);
}
else ... {
Oldfile.renameto (NewFile);
}
}
}
Six. Read the file
1. Using FileInputStream to read files


public string Fileinputstreamdemo (string path) throws IOException ... {
File File=new file (path);
if (!file.exists () | | | File.isdirectory ())
throw new FileNotFoundException ();
FileInputStream fis=new fileinputstream (file);
byte[] buf = new byte[1024];
StringBuffer sb=new StringBuffer ();
while ((Fis.read (BUF))!=-1) ... {
Sb.append (New String (BUF));
Buf=new byte[1024];//regenerate to avoid duplication with last-read data
}
return sb.tostring ();
}
2. Read with BufferedReader

In IO operation, using BufferedReader and bufferedwriter efficiency will be a bit higher



public string Bufferedreaderdemo (string path) throws IOException ... {
File File=new file (path);
if (!file.exists () | | | File.isdirectory ())
throw new FileNotFoundException ();
BufferedReader br=new BufferedReader (new FileReader (file));
String Temp=null;
StringBuffer sb=new StringBuffer ();
Temp=br.readline ();
while (Temp!=null) ... {
Sb.append (temp+ "");
Temp=br.readline ();
}
return sb.tostring ();
}


3. Reading an XML file with dom4j


Public Document readXml (String path) throws Documentexception, IOException ... {
File File=new file (path);
BufferedReader BufferedReader = new BufferedReader (new FileReader (file));
Saxreader Saxreader = new Saxreader ();
Document document = (document) Saxreader.read (BufferedReader);
Bufferedreader.close ();
return document;
}
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 CreateFile (String path,string filename) 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 void Deldir (String path) ... {
File Dir=new file (path);
if (dir.exists ()) ... {
File[] Tmp=dir.listfiles ();
for (int i=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

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.