Write a string to a file:
Code:
- Import java. Io .*;
- Class fileoutputdemo {
- Public static void main (string ARGs []) {
- Fileoutputstream out; // declare a file output object
- Printstream P; // declare a print Stream Object
- Try {
- // Connected to "myfile.txt"
- Out = new fileoutputstream ("C:/a.txt ");
- // Connect print stream to the output stream
- P = new printstream (out );
- P. println ("this is written to a file ");
- P. Close ();
- } Catch (exception e ){
- System. Err. println ("error writing to file ");
- }
- }
- }
Java reads the file content:
Code:
- Import java. Io .*;
- Class fileinputdemo {
- Public static void main (string ARGs []) {
- // Args. length is equivalent to argc in C
- Try {
- // Open the file that is the first command line parameter
- Fileinputstream fstream = new fileinputstream ("C:/B .txt ");
- // Convert our input stream to a datainputstream
- Datainputstream in = new datainputstream (fstream );
- // Continue to read lines while there are still some left
- // Read
- String S = "";
- While (in. Available ()! = 0 ){
- // Print file line to screen
- S = in. Readline ();
- System. Out. println (s );
- }
- // String RegEx = "src = /"";
- // S = S. replaceall (RegEx, "str =/" http://article.star.com: 8081/temp /");
- In. Close ();
- } Catch (Exception e ){
- System. err. println ("File input error ");
- }
- }
- }