Java file read/write operations

Source: Internet
Author: User
Package com. RDPs. Dev. fliu. server;

Import java. Io. bufferedwriter;
Import java. Io. file;
Import java. Io. fileinputstream;
Import java. Io. filenotfoundexception;
Import java. Io. filewriter;
Import java. Io. ioexception;

/**
* File test class.
* @ Author Frank
* @ Since 11/18/2010
**/
Public class filetest {

Public static void main (string [] ARGs ){
String content = filetest. readfile ("/home/Frank/desktop/testfile ");
System. Out. println (content );
Filetest. writefile ("Write test data into file.", "/home/Frank/desktop", "testfile ");
}

/**
* Write the content to a file.
**/
Public static Boolean writefile (string content, string path, string filename ){
File file = new file (PATH );
System. Out. println ("the file's location is:" + path + "/" + filename );
Try {
Bufferedwriter BW = new bufferedwriter (New filewriter (File + "/" + filename, true ));
Bw. Write (content );
Bw. Write ("");
Bw. Flush ();
Bw. Close ();
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
Return true;
}

/**
* Read content from a file.
**/
Public static string readfile (string path ){
Stringbuilder content = new stringbuilder ("");
File file = new file (PATH );
Try {
Fileinputstream FCM = new fileinputstream (File );
Byte [] bytearray = new byte [FCM. Available ()];
Int bytetotal = Fi. Available ();
While (FCM. Read (bytearray, 0, bytetotal )! =-1 ){
String temp = new string (bytearray, 0, bytetotal );
Content. append (temp );
}
} Catch (filenotfoundexception e ){
System. Out. println ("Frank's file not exits ....");
E. printstacktrace ();
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
Return content. tostring ();
}
}

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.