Java file read/write operations

Source: Internet
Author: User

1. Obtain information entered by the console user

Public String getinputmessage () throws ioexception ...{
System. Out. println ("Enter your command ");
Byte buffer [] = new byte [1024];
Int COUNT = system. In. Read (buffer );
Char [] CH = new char [count-2]; // the last two digits are the Terminator, delete not
For (INT I = 0; I <count-2; I ++)
Ch [I] = (char) buffer [I];
String STR = new string (CH );
Return STR;
}
The user input information can be returned. The disadvantage is that Chinese input is not supported and further improvement is needed.

Ii. Copy an object
1. copy a file 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 is tested and supports Chinese processing and can be copied to multiple formats, such as txt, XML, JPG, and Doc.

3. Write files

1. Use printstream to write files


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
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 line" + I + ": the 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 be used to set the encoding to effectively solve Chinese problems.
Iv. File rename

Public void renamefile (string path, string oldname, string newname )...{
If (! Oldname. Equals (newname)... {// It is necessary to rename a new file name that is different from the previous one.
File oldfile = new file (path + "/" + oldname );
File newfile = new file (path + "/" + newname );
If (newfile. exists () // if there is already a file in the directory with the same name as the new file, rename is not allowed
System. Out. println (newname + "already exists! ");
Else ...{
Oldfile. renameto (newfile );
}
}
}

5. Transfer file directory
The transfer file directory is not the same as the copy file. The copy file exists in both directories after the copy, but the transfer file directory exists only in the new directory after the transfer.

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 it is in the directory to be transferred, the file to be transferred already exists
If (cover) // Overwrite
Oldfile. renameto (newfile );
Else
System. Out. println ("already exists in the new directory:" + filename );
}
Else ...{
Oldfile. renameto (newfile );
}
}
}
6. Read files
1. Use 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 FCM = new fileinputstream (File );
Byte [] Buf = new byte [1, 1024];
Stringbuffer sb = new stringbuffer ();
While (FCM. Read (BUF ))! =-1 )...{
SB. append (new string (BUF ));
Buf = new byte [1024]; // regenerate to avoid duplication with the data read last time
}
Return sb. tostring ();
}
2. Read data using bufferedreader

In Io operations, bufferedreader and bufferedwriter are more efficient.



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


Public document readxml (string path) throws into entexception, ioexception ...{
File file = new file (PATH );
Bufferedreader = new bufferedreader (New filereader (File ));
Saxreader = new saxreader ();
Document document = (document) saxreader. Read (bufferedreader );
Bufferedreader. Close ();
Return document;
}
7. 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 ();
}
8. delete files (directories)
1. delete an object
Public void delfile (string path, string filename )...{
File file = new file (path + "/" + filename );
If (file. exists () & file. isfile ())
File. Delete ();
}
2. delete a directory
To delete a directory using the delete () method of the file class, you must ensure that there are no files or subdirectories in the directory; otherwise, the deletion fails. Therefore, in actual applications, we need to delete the directory, you must recursively Delete All subdirectories and files in the directory before deleting 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 ();
}
}

From: http://www.cnblogs.com/zhuocheng/archive/2011/12/12/2285290.html

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.