Example of reading/writing a file text file in Java

Source: Internet
Author: User

The following describes how to read/write file text files in Java. Here, both the read and write files in Java are based on the writable stream and mainly use the following classes:

1. FileReader ---- read the volume stream
2. FileWriter ---- write the volume stream
3. BufferedReader ---- buffer the input of a specified file
Methods of this class include:
Void close ()
Close the stream.
Void mark (int readAheadLimit)
Mark the current position in the stream.
Boolean markSupported ()
Determines whether the stream supports the mark () operation (which must support) int read ()
Read a single character.
Int read (char [] cbuf, int off, int len)
Read characters into a part of the array.
String readLine ()
Read a text line.
Boolean ready ()
Determine whether the stream is ready for reading.
Void reset ()
Resets the stream to the latest tag.
Long skip (long n)
Skip characters.
4. BufferedWriter ---- buffer the output of the file
Methods of this class include:
Void close ()
Close the stream.
Void flush ()
Refresh the buffer of the stream.
Void newLine ()
Write a line separator.
Void write (char [] cbuf, int off, int len)
Write a part of the character array.
Void write (int c)
Write a single character.
Void write (String s, int off, int len)
Write a part of the string.

 

For example:

The Code is as follows: Copy code


Package aillo;
Import java. io .*;
Public class FileWriterReader {
// Function: Read the content of the f:/aillo.txt file (one row) and write the content to f:/jackie.txt.
// Knowledge point: read and write files in java --- <in the form of streams>
Public static void main (String [] args ){
Try {
FileReader fr = new FileReader ("f:/aillo.txt"); // creates a FileReader object to read the latest stream.
BufferedReader br = new BufferedReader (fr); // buffer the input of the specified file
FileWriter fw = new FileWriter ("f:/jackie.txt"); // creates a FileWriter object for writing to the volume stream.
BufferedWriter bw = new BufferedWriter (fw); // buffer the output of the file
String myreadline; // defines a String-type variable to read a row each time.
While (br. ready ()){
Myreadline = br. readLine (); // read a row
Bw. write (myreadline); // write the file
Bw. newLine ();
System. out. println (myreadline); // output on the screen
}
Bw. flush (); // refresh the buffer of the stream
Bw. close ();
Br. close ();
Fw. close ();
Br. close ();
Fr. close ();

} Catch (IOException e ){
E. printStackTrace ();
}
}
}

Java example of reading/writing a file text file

The Code is as follows: Copy code

/*
* Simple example of reading/writing text files
* There are three examples:
* 1. Example of reading a file into memory (StringBuffer here)
* 2. Write the text in the content to a file
* 3. Read the content of one file and write it to another file.
* It also shows that if the content read from the input stream is written to the output stream (Text Stream only)
* The three examples can exist independently, so you can only view one of them as needed.
*/

Import java. io. BufferedReader;
Import java. io. FileInputStream;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java. io. InputStreamReader;
Import java. io. OutputStream;
Import java. io. OutputStreamWriter;
Import java. io. PrintStream;
Import java. io. PrintWriter;

Public final class AccessTextFile {

/**
* 1. Read the text in the stream into a StringBuffer.
* @ Throws IOException
*/
Public void readToBuffer (StringBuffer buffer, InputStream is)
Throws IOException {
String line; // used to save the content read by each row
BufferedReader reader = new BufferedReader (new InputStreamReader (is ));
Line = reader. readLine (); // read the first row
While (line! = Null) {// If line is null, the read is complete.
Buffer. append (line); // Add the read content to the buffer.
Buffer. append ("n"); // Add a line break
Line = reader. readLine (); // read the next row
}
}

/**
* 2. Demonstrate reading the content in StringBuffer into the stream
*/
Public void writeFromBuffer (StringBuffer buffer, OutputStream OS ){
// Use PrintStream to conveniently output content to the output stream
// Its object usage is the same as that of System. out.
// (System. out itself is a PrintStream object)
PrintStream ps = new PrintStream (OS );
Ps. print (buffer. toString ());
}

/**
* 3 *. Copy the content from the input stream to the input stream.
* @ Throws IOException
*/
Public void copyStream (InputStream is, OutputStream OS) throws IOException {
// For the read process, see the comments in readToBuffer.
String line;
BufferedReader reader = new BufferedReader (new InputStreamReader (is ));
PrintWriter writer = new PrintWriter (new OutputStreamWriter (OS ));
Line = reader. readLine ();
While (line! = Null ){
Writer. println (line );
Line = reader. readLine ();
}
Writer. flush (); // finally, make sure to write everything in the output stream.
// Writer is not disabled because the OS is passed in from outside.
// Since it is not opened from here, it will not be closed from here
// If the writer is closed, the OS encapsulated in it will be shut down.
}

/**
* 3. Call the copyStream (InputStream, OutputStream) method to copy text files.
*/
Public void copyTextFile (String inFilename, String outFilename)
Throws IOException {
// Generate the corresponding input/output stream based on the input/output file
InputStream is = new FileInputStream (inFilename );
OutputStream OS = new FileOutputStream (outFilename );
CopyStream (is, OS); // use copyStream to copy content
Is. close (); // is enabled here, so you need to close
OS. close (); // OS is enabled here, so you need to disable
}

Public static void main (String [] args) throws IOException {
Int sw = 1; // three test options
AccessTextFile test = new AccessTextFile ();

Switch (sw ){
Case 1: // test read
{
InputStream is = new FileInputStream ("E: \ test.txt ");
StringBuffer buffer = new StringBuffer ();
Test. readToBuffer (buffer, is );
System. out. println (buffer); // write the content in the buffer.
Is. close ();
Break;
}
Case 2: // test write
{
StringBuffer buffer = new StringBuffer ("Only a testn ");
Test. writeFromBuffer (buffer, System. out );
Break;
}
Case 3: // test copy
{
Test. copyTextFile ("E: \ test.txt", "E: \ r.txt ");
}
Break;
}
}

}

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.