Java read-Write file creation folder Multiple methods examples detailed _java

Source: Internet
Author: User
Tags readline stringbuffer

There are garbled, please fix instead

BufferedReader br = new BufferedReader (New InputStreamReader (
New FileInputStream (path), "GBK"));

I. Obtaining information entered by the console user

Copy Code code as follows:

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 digits as Terminator, delete no
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 not support Chinese input, need further improvement.

Two. copy files

1. Copying files in a file flow manner

Copy Code code as follows:

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 to support Chinese processing and can be replicated in a variety of formats such as Txt,xml,jpg,doc

Three. Write a document

1. Use PrintStream to write files

Copy Code code as follows:

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 is" +i+ "line");
catch (FileNotFoundException e) ... {
E.printstacktrace ();
}
}

2. Use StringBuffer to write files

Copy Code code as follows:

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 first" +i+ "line: The various methods described earlier are not closed, why is always a strange problem");
Out.write (Sb.tostring (). GetBytes ("Utf-8"));
}
Out.close ();
}

This method can be used to set the code to effectively solve the Chinese problem.

Four. File renaming

Copy Code code as follows:

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

Five. Transfer file directory

The staging file directory is not the same as copying the file, the copy file exists after both directories are replicated, and the staging file directory is transferred, only the file exists in the new directory.

Copy Code code as follows:

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 there is already a pending file in the directory to be transferred
if (cover)//overwrite
Oldfile.renameto (NewFile);
Else
System.out.println ("already exists under the new directory:" +filename);
}
else ... {
Oldfile.renameto (NewFile);
}
}
}

Six. Read the document

1. read files using FileInputStream

Copy Code code as follows:

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];//rebuild to avoid duplication with last-read data
}
return sb.tostring ();
}

2. Using BufferedReader to read

In IO operations, using BufferedReader and bufferedwriter efficiencies would be a bit higher

Copy Code code as follows:

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. read XML files using dom4j

Copy Code code as follows:

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

Copy Code code as follows:

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

2. Create a new file

Copy Code code as follows:

public void CreateFile (String path,string filename) throws ioexception{
File File=new file (path+ "/" +filename);
if (!file.exists ())
File.createnewfile ();
}

Eight. Delete file (directory)

1. Delete Files

Copy Code code as follows:

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

2. Delete Directory

To delete a directory using the Delete () method of the file class, you must ensure that there are no files or subdirectories under that directory, or the deletion fails, so in practice, we delete the directory, and we have to delete all subdirectories and files in the directory recursively, and then delete the directory.

Copy Code code as follows:

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 ();
}
}

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.