Java file read/write operations

Source: Internet
Author: User

Write a string to a file:

Code:
  1. Import java. Io .*;
  2. Class fileoutputdemo {
  3. Public static void main (string ARGs []) {
  4. Fileoutputstream out; // declare a file output object
  5. Printstream P; // declare a print Stream Object
  6. Try {
  7. // Connected to "myfile.txt"
  8. Out = new fileoutputstream ("C:/a.txt ");
  9. // Connect print stream to the output stream
  10. P = new printstream (out );
  11. P. println ("this is written to a file ");
  12. P. Close ();
  13. } Catch (exception e ){
  14. System. Err. println ("error writing to file ");
  15. }
  16. }
  17. }

Java reads the file content:

Code:
  1. Import java. Io .*;
  2. Class fileinputdemo {
  3. Public static void main (string ARGs []) {
  4. // Args. length is equivalent to argc in C
  5. Try {
  6. // Open the file that is the first command line parameter
  7. Fileinputstream fstream = new fileinputstream ("C:/B .txt ");
  8. // Convert our input stream to a datainputstream
  9. Datainputstream in = new datainputstream (fstream );
  10. // Continue to read lines while there are still some left
  11. // Read
  12. String S = "";
  13. While (in. Available ()! = 0 ){
  14. // Print file line to screen
  15. S = in. Readline ();
  16. System. Out. println (s );
  17. }
  18. // String RegEx = "src = /"";
  19. // S = S. replaceall (RegEx, "str =/" http://article.star.com: 8081/temp /");
  20. In. Close ();
  21. } Catch (Exception e ){
  22. System. err. println ("File input error ");
  23. }
  24. }
  25. }

 

 

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.