Java file read/write Methods

Source: Internet
Author: User

There are several common methods for reading and writing Java files, such as InputStream/OutputStream and BufferedReader, I will introduce their usage examples in detail below.

There are several common methods to read and write files:

1. byte read/write (InputStream/OutputStream) and character read (FileReader/FileWriter)

FileInputStream's read (buffer) method, each time from the source program file OpenFile. java reads 512 bytes, stores them in the buffer, and then displays the new String (buffer) constructed with the buffer value on the screen. For example, the program is shown in biz.1cn.stream. create the testfile.txt file in the root directory to run properly.

The Code is as follows: Copy code

Package biz.1cn. stream;
Import java. io. FileInputStream;
Import java. io. IOException;
/**
* @ Author chenrz (simon)
* @ Date 2006-29
* <P>
* Example of a JAVA byte stream-reading a file
* </P>
*/
Public class ReadFile {
Public static void main (String [] args ){
Try {
// Create a file input stream object
FileInputStream is = new FileInputStream ("TestFile.txt ");
// Set the number of bytes to read
Int n = 512;
Byte buffer [] = new byte [n];
// Read the input stream
While (is. read (buffer, 0, n )! =-1) & (n> 0 )){
System. out. print (new String (buffer ));
}
System. out. println ();
// Close the input stream
Is. close ();
} Catch (IOException ioe ){
System. out. println (ioe );
} Catch (Exception e ){
System. out. println (e );
}
}
}

Hosts file ):

The Code is as follows: Copy code

Package biz.1cn. stream;
Import java. io. FileOutputStream;
Import java. io. IOException;
/**
* @ Author chenrz (simon)
* @ Date 2006-29
* <P>
* JAVA byte stream example-write a file (www.1cn. biz)
* </P>
*/
Public class WriteFile {
Public static void main (String [] args ){
Try {
System. out. print ("Enter the content of the file to be saved :");
Int count, n = 512;
Byte buffer [] = new byte [n];
// Read the standard input stream
Count = System. in. read (buffer );
// Create a file output stream object
FileOutputStream OS = new FileOutputStream ("WriteFile.txt ");
// Write the output stream
OS. write (buffer, 0, count );
// Close the output stream
OS. close ();
System. out. println ("saved to writefile.txt! ");
} Catch (IOException ioe ){
System. out. println (ioe );
} Catch (Exception e ){
System. out. println (e );
}
}
}

2. character reading (FileReader/FileWriter)

Example

The Code is as follows: Copy code

Package test;

Import java. io. File;
Import java. io. FileReader;
Import java. io. FileWriter;
Import java. io. IOException;

Public class Test {

Public static void main (String arg []) {
String fileName = "E: sharetest.txt ";
String writeData = "HelloWorld! Rnnihao my memory is 3 GB ";
File file = new File (fileName );
If (file. exists ()){
File. delete ();
}

Char [] byteOutData = writeData. toCharArray ();
Char [] byteInData = new char [50];
Int length = 0;

Try {
File. createNewFile ();
If (file. exists () & file. canWrite ()){
FileWriter fileWrite = new FileWriter (file );
FileWrite. write (byteOutData );
FileWrite. close ();
}
If (file. exists () & file. canRead ()){
FileReader fileReader = new FileReader (file );
While (length = fileReader. read (byteInData ))! =-1 ){
System. out. print (new String (byteInData, 0, length ));
}

FileReader. close ();
}

} Catch (IOException e ){
System. out. println ("IOException occur ");
E. getMessage ();
}
}
}


3. row reading (BufferedReader/BufferedWriter)


Code (read as an example ):

The Code is as follows: Copy code


Import java. io. BufferedReader;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. FileReader;
Import java. io. IOException;
Import java. io. InputStream;
/**
* <B> File Reading Class </B> <br/>
* 1. Read File Content by byte <br/>
* 2. Read File Content by character <br/>
* 3. Read File Content by row <br/>
* @ Author qin_xijuan
*
*/
Public class FileOperate {

Private static final String FILE_PATH = "d:/work/the List of Beautiful Music.txt ";

/**
* Reading file content in bytes
* @ Param filePath: Path of the file to be read
*/
Public static void readFileByByte (String filePath ){
File file = new File (filePath );
// InputStream: This abstract class represents the superclass of all classes of the byte input stream.
InputStream ins = null;
Try {
// FileInputStream: obtains the input bytes from a file in the file system.
Ins = new FileInputStream (file );
Int temp;
// Read (): The Next byte that reads data from the input stream.
While (temp = ins. read ())! =-1 ){
System. out. write (temp );
}
} Catch (Exception e ){
E. getStackTrace ();
} Finally {
If (ins! = Null ){
Try {
Ins. close ();
} Catch (IOException e ){
E. getStackTrace ();
}
}
}
}

/**
* Read File Content in characters
* @ Param filePath
*/
Public static void readFileByCharacter (String filePath ){
File file = new File (filePath );
// FileReader: a convenient class for reading character files.
FileReader reader = null;
Try {
Reader = new FileReader (file );
Int temp;
While (temp = reader. read ())! =-1 ){
If (char) temp )! = 'R '){
System. out. print (char) temp );
}
}
} Catch (IOException e ){
E. getStackTrace ();
} Finally {
If (reader! = Null ){
Try {
Reader. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}

/**
* Read the file content in the unit of behavior
* @ Param filePath
*/
Public static void readFileByLine (String filePath ){
File file = new File (filePath );
// BufferedReader: Read text from the character input stream and buffer each character to efficiently read characters, arrays, and rows.
BufferedReader buf = null;
Try {
// FileReader: a convenient class for reading character files.
Buf = new BufferedReader (new FileReader (file ));
// Buf = new BufferedReader (new InputStreamReader (new FileInputStream (file )));
String temp = null;
While (temp = buf. readLine ())! = Null ){
System. out. println (temp );
}
} Catch (Exception e ){
E. getStackTrace ();
} Finally {
If (buf! = Null ){
Try {
Buf. close ();
} Catch (IOException e ){
E. getStackTrace ();
}
}
}
}

Public static void main (String args []) {
ReadFileByByte (FILE_PATH );
ReadFileByCharacter (FILE_PATH );
ReadFileByLine (FILE_PATH );
}
}

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.